/**
   * Offer to send some dedicated intent data to an existing room
   *
   * @param fromActivity the caller activity
   * @param intent the intent param
   */
  public static void sendFilesTo(final Activity fromActivity, final Intent intent) {
    if (Matrix.getMXSessions(fromActivity).size() == 1) {
      sendFilesTo(fromActivity, intent, Matrix.getMXSession(fromActivity, null));
    } else if (fromActivity instanceof FragmentActivity) {
      FragmentManager fm = ((FragmentActivity) fromActivity).getSupportFragmentManager();

      AccountsSelectionDialogFragment fragment =
          (AccountsSelectionDialogFragment)
              fm.findFragmentByTag(MXCActionBarActivity.TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG);
      if (fragment != null) {
        fragment.dismissAllowingStateLoss();
      }

      fragment = AccountsSelectionDialogFragment.newInstance(Matrix.getMXSessions(fromActivity));

      fragment.setListener(
          new AccountsSelectionDialogFragment.AccountsListener() {
            @Override
            public void onSelected(final MXSession session) {
              fromActivity.runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      sendFilesTo(fromActivity, intent, session);
                    }
                  });
            }
          });

      fragment.show(fm, MXCActionBarActivity.TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG);
    }
  }
  /**
   * Logout the current user.
   *
   * @param activity the caller activity
   */
  public static void logout(Activity activity) {
    stopEventStream(activity);

    try {
      ShortcutBadger.setBadge(activity, 0);
    } catch (Exception e) {
    }

    // warn that the user logs out
    Collection<MXSession> sessions = Matrix.getMXSessions(activity);
    for (MXSession session : sessions) {
      // Publish to the server that we're now offline
      MyPresenceManager.getInstance(activity, session).advertiseOffline();
      MyPresenceManager.remove(session);
    }

    // clear the preferences
    PreferenceManager.getDefaultSharedPreferences(activity).edit().clear().commit();

    // clear credentials
    Matrix.getInstance(activity).clearSessions(activity, true);

    // reset the GCM
    Matrix.getInstance(activity).getSharedGcmRegistrationManager().reset();

    // reset the contacts
    PIDsRetriever.getIntance().reset();
    ContactsManager.reset();

    MXMediasCache.clearThumbnailsCache(activity);

    // go to login page
    activity.startActivity(new Intent(activity, LoginActivity.class));
    activity.finish();
  }
 public static void goToRoomPage(
     final String matrixId,
     final String roomId,
     final Activity fromActivity,
     final Intent intentParam) {
   goToRoomPage(Matrix.getMXSession(fromActivity, matrixId), roomId, fromActivity, intentParam);
 }
  public static void startEventStreamService(Context context) {
    // the events stream service is launched
    // either the application has never be launched
    // or the service has been killed on low memory
    if (EventStreamService.getInstance() == null) {
      ArrayList<String> matrixIds = new ArrayList<String>();
      Collection<MXSession> sessions =
          Matrix.getInstance(context.getApplicationContext()).getSessions();

      if ((null != sessions) && (sessions.size() > 0)) {
        Log.d(LOG_TAG, "restart EventStreamService");

        for (MXSession session : sessions) {
          Boolean isSessionReady = session.getDataHandler().getStore().isReady();

          if (!isSessionReady) {
            session.getDataHandler().getStore().open();
          }

          // session to activate
          matrixIds.add(session.getCredentials().userId);
        }

        Intent intent = new Intent(context, EventStreamService.class);
        intent.putExtra(
            EventStreamService.EXTRA_MATRIX_IDS, matrixIds.toArray(new String[matrixIds.size()]));
        intent.putExtra(
            EventStreamService.EXTRA_STREAM_ACTION,
            EventStreamService.StreamAction.START.ordinal());
        context.startService(intent);
      }
    }
  }
 public static void goToOneToOneRoom(
     final String matrixId,
     final String otherUserId,
     final Activity fromActivity,
     final ApiCallback<Void> callback) {
   goToOneToOneRoom(
       Matrix.getMXSession(fromActivity, matrixId), otherUserId, fromActivity, callback);
 }
  public static void goToRoomPage(
      final MXSession aSession,
      final String roomId,
      final Activity fromActivity,
      final Intent intentParam) {
    // check first if the 1:1 room already exists
    MXSession session = (aSession == null) ? Matrix.getMXSession(fromActivity, null) : aSession;

    // sanity check
    if ((null == session) || !session.isActive()) {
      return;
    }

    final MXSession fSession = session;

    Room room = session.getDataHandler().getRoom(roomId);

    // do not open a leaving room.
    // it does not make.
    if ((null != room) && (room.isLeaving())) {
      return;
    }

    fromActivity.runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            // if the activity is not the home activity
            if (!(fromActivity instanceof HomeActivity)) {
              // pop to the home activity
              Intent intent = new Intent(fromActivity, HomeActivity.class);
              intent.setFlags(
                  android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
                      | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP);
              intent.putExtra(HomeActivity.EXTRA_JUMP_TO_ROOM_ID, roomId);
              intent.putExtra(HomeActivity.EXTRA_JUMP_MATRIX_ID, fSession.getCredentials().userId);
              if (null != intentParam) {
                intent.putExtra(HomeActivity.EXTRA_ROOM_INTENT, intentParam);
              }
              fromActivity.startActivity(intent);
            } else {
              // already to the home activity
              // so just need to open the room activity
              Intent intent = new Intent(fromActivity, RoomActivity.class);
              intent.putExtra(RoomActivity.EXTRA_ROOM_ID, roomId);
              intent.putExtra(RoomActivity.EXTRA_MATRIX_ID, fSession.getCredentials().userId);
              if (null != intentParam) {
                intent.putExtra(HomeActivity.EXTRA_ROOM_INTENT, intentParam);
              }
              fromActivity.startActivity(intent);
            }
          }
        });
  }
  /** refresh the profile thumbnail */
  private void refreshProfileThumbnail() {
    mThumbnailImageView.setImageResource(R.drawable.ic_contact_picture_holo_light);

    if (mMember.avatarUrl != null) {
      int size = getResources().getDimensionPixelSize(R.dimen.profile_avatar_size);
      Matrix.getInstance(this)
          .getMediasCache()
          .loadAvatarThumbnail(
              mSession.getHomeserverConfig(), mThumbnailImageView, mMember.avatarUrl, size);
    }
  }
  public static void logout(Activity activity, MXSession session, Boolean clearCredentials) {
    if (session.isActive()) {
      // stop the service
      EventStreamService eventStreamService = EventStreamService.getInstance();
      ArrayList<String> matrixIds = new ArrayList<String>();
      matrixIds.add(session.getMyUser().userId);
      eventStreamService.stopAccounts(matrixIds);

      // Publish to the server that we're now offline
      MyPresenceManager.getInstance(activity, session).advertiseOffline();
      MyPresenceManager.remove(session);

      // unregister from the GCM.
      Matrix.getInstance(activity)
          .getSharedGcmRegistrationManager()
          .unregisterSession(session, null);

      // clear credentials
      Matrix.getInstance(activity).clearSession(activity, session, clearCredentials);
    }
  }
 public static Boolean shouldRestartApp() {
   EventStreamService eventStreamService = EventStreamService.getInstance();
   return !Matrix.hasValidSessions() || (null == eventStreamService);
 }
  public static void goToOneToOneRoom(
      final MXSession aSession,
      final String otherUserId,
      final Activity fromActivity,
      final ApiCallback<Void> callback) {
    // sanity check
    if (null == otherUserId) {
      return;
    }

    // check first if the 1:1 room already exists
    MXSession session = (aSession == null) ? Matrix.getMXSession(fromActivity, null) : aSession;

    // no session is provided
    if (null == session) {
      // get the default one.
      session = Matrix.getInstance(fromActivity.getApplicationContext()).getDefaultSession();
    }

    // sanity check
    if ((null == session) || !session.isActive()) {
      return;
    }

    final MXSession fSession = session;

    // so, list the existing room, and search the 2 users room with this other users
    String roomId = null;
    Collection<Room> rooms = session.getDataHandler().getStore().getRooms();

    for (Room room : rooms) {
      Collection<RoomMember> members = room.getMembers();

      if (members.size() == 2) {
        for (RoomMember member : members) {
          if (member.getUserId().equals(otherUserId)) {
            roomId = room.getRoomId();
            break;
          }
        }
      }
    }

    // the room already exists -> switch to it
    if (null != roomId) {
      CommonActivityUtils.goToRoomPage(session, roomId, fromActivity, null);

      // everything is ok
      if (null != callback) {
        callback.onSuccess(null);
      }
    } else {
      session.createRoom(
          null,
          null,
          RoomState.VISIBILITY_PRIVATE,
          null,
          new SimpleApiCallback<String>(fromActivity) {

            @Override
            public void onSuccess(String roomId) {
              final Room room = fSession.getDataHandler().getRoom(roomId);

              room.invite(
                  otherUserId,
                  new SimpleApiCallback<Void>(this) {
                    @Override
                    public void onSuccess(Void info) {
                      CommonActivityUtils.goToRoomPage(
                          fSession, room.getRoomId(), fromActivity, null);

                      callback.onSuccess(null);
                    }

                    @Override
                    public void onMatrixError(MatrixError e) {
                      if (null != callback) {
                        callback.onMatrixError(e);
                      }
                    }

                    @Override
                    public void onNetworkError(Exception e) {
                      if (null != callback) {
                        callback.onNetworkError(e);
                      }
                    }

                    @Override
                    public void onUnexpectedError(Exception e) {
                      if (null != callback) {
                        callback.onUnexpectedError(e);
                      }
                    }
                  });
            }

            @Override
            public void onMatrixError(MatrixError e) {
              if (null != callback) {
                callback.onMatrixError(e);
              }
            }

            @Override
            public void onNetworkError(Exception e) {
              if (null != callback) {
                callback.onNetworkError(e);
              }
            }

            @Override
            public void onUnexpectedError(Exception e) {
              if (null != callback) {
                callback.onUnexpectedError(e);
              }
            }
          });
    }
  }
 public static void disconnect(Activity activity) {
   stopEventStream(activity);
   activity.finish();
   Matrix.getInstance(activity).mHasBeenDisconnected = true;
 }
 /**
  * Return the used medias cache. This method can be overridden to use another medias cache
  *
  * @return the used medias cache
  */
 public MXMediasCache getMXMediasCache() {
   return Matrix.getInstance(getActivity()).getMediasCache();
 }