Exemplo n.º 1
0
  public void run(String[] args) {

    DatabaseFactory factory = new DatabaseFactory();
    if (System.getProperty("user.dir").isEmpty()) {
      System.out.println("user.dir is incorrect");
    }
    if (System.getProperty("fizteh.db.dir").isEmpty()) {
      System.out.println("fizteh.db.dir is incorrect");
    }

    Path pathDirection =
        Paths.get(System.getProperty("user.dir")).resolve(System.getProperty("fizteh.db.dir"));

    String dir = pathDirection.toString();

    DatabaseProvider dProvider = factory.create(dir);

    if (args.length == 0) {

      interactiveMode(dProvider);
    } else {

      pocketMode(args, dProvider);
    }
  }
Exemplo n.º 2
0
  public void trimThread(long threadId, int length) {
    Log.w("ThreadDatabase", "Trimming thread: " + threadId + " to: " + length);
    Cursor cursor = null;

    try {
      cursor = DatabaseFactory.getMmsSmsDatabase(context).getConversation(threadId);

      if (cursor != null && length > 0 && cursor.getCount() > length) {
        Log.w("ThreadDatabase", "Cursor count is greater than length!");
        cursor.moveToPosition(length - 1);

        long lastTweetDate =
            cursor.getLong(cursor.getColumnIndexOrThrow(MmsSmsColumns.NORMALIZED_DATE_RECEIVED));

        Log.w("ThreadDatabase", "Cut off tweet date: " + lastTweetDate);

        DatabaseFactory.getSmsDatabase(context)
            .deleteMessagesInThreadBeforeDate(threadId, lastTweetDate);
        DatabaseFactory.getMmsDatabase(context)
            .deleteMessagesInThreadBeforeDate(threadId, lastTweetDate);

        update(threadId, false);
        notifyConversationListeners(threadId);
      }
    } finally {
      if (cursor != null) cursor.close();
    }
  }
Exemplo n.º 3
0
  public void deleteAllThreads() {
    DatabaseFactory.getAttachmentDatabase(context).deleteAllAttachments();
    DatabaseFactory.getMmsAddressDatabase(context).deleteAllAddresses();

    SQLiteDatabase database = databaseHelper.getWritableDatabase();
    database.delete(TABLE_NAME, null, null);
  }
  private static void migrateConversation(
      Context context,
      MasterSecret masterSecret,
      Handler handler,
      long theirThreadId,
      long ourThreadId) {
    SmsDatabase ourSmsDatabase = DatabaseFactory.getSmsDatabase(context);
    Cursor cursor = null;

    try {
      Uri uri = Uri.parse("content://sms/conversations/" + theirThreadId);
      cursor = context.getContentResolver().query(uri, null, null, null, null);
      SQLiteDatabase transaction = ourSmsDatabase.beginTransaction();
      SQLiteStatement statement = ourSmsDatabase.createInsertStatement(transaction);

      while (cursor != null && cursor.moveToNext()) {
        getContentValuesForRow(context, masterSecret, cursor, ourThreadId, statement);
        statement.execute();

        Message msg =
            handler.obtainMessage(SECONDARY_PROGRESS_UPDATE, 10000 / cursor.getCount(), 0);
        handler.sendMessage(msg);
      }

      ourSmsDatabase.endTransaction(transaction);
      DatabaseFactory.getThreadDatabase(context).update(ourThreadId);
      DatabaseFactory.getThreadDatabase(context).notifyConversationListeners(ourThreadId);

    } finally {
      if (cursor != null) cursor.close();
    }
  }
Exemplo n.º 5
0
 /* takes the two experiment ids for which to retrieve data.
  */
 public PairedSQLData(int one, int two) throws SQLException {
   exptone = one;
   expttwo = two;
   try {
     corecxn = DatabaseFactory.getConnection("core");
   } catch (UnknownRoleException ex) {
     throw new DatabaseException("Couldn't connect with role core", ex);
   } catch (SQLException ex) {
     throw new DatabaseException("Couldn't connect to database for role core", ex);
   }
   try {
     chipcxn = DatabaseFactory.getConnection("chipchip");
     basicstmt =
         chipcxn.prepareStatement(
             "select a.channelone, a.channeltwo, a.ratio, b.channelone, b.channeltwo, b.ratio "
                 + " from data a, data b where a.probe = b.probe and a.experiment = ? and "
                 + " b.experiment = ?");
     samplestmt =
         chipcxn.prepareStatement(
             "select * from (select a.channelone, a.channeltwo, a.ratio, b.channelone, b.channeltwo, b.ratio, dbms_random.value as randval "
                 + " from data a, data b where a.probe = b.probe and a.experiment = ? and "
                 + " b.experiment = ? order by dbms_random.value) where randval < ?");
     limitstmt =
         chipcxn.prepareStatement(
             "select aone, atwo, arat, bone, btwo, brat from (select a.channelone aone, a.channeltwo atwo, a.ratio arat, b.channelone bone, b.channeltwo btwo, b.ratio brat "
                 + " from data a, data b where a.probe = b.probe and a.experiment = ? and "
                 + " b.experiment = ? order by dbms_random.value) where rownum < ?");
   } catch (UnknownRoleException ex) {
     throw new DatabaseException("Couldn't connect with role chipchip", ex);
   } catch (SQLException ex) {
     throw new DatabaseException("Couldn't connect to database for role chipchip", ex);
   }
 }
Exemplo n.º 6
0
  private @NonNull Pair<Long, Long> insertCallLog(
      @NonNull String number, long type, boolean unread) {
    Recipients recipients = RecipientFactory.getRecipientsFromString(context, number, true);
    long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);

    ContentValues values = new ContentValues(6);
    values.put(ADDRESS, number);
    values.put(ADDRESS_DEVICE_ID, 1);
    values.put(DATE_RECEIVED, System.currentTimeMillis());
    values.put(DATE_SENT, System.currentTimeMillis());
    values.put(READ, unread ? 0 : 1);
    values.put(TYPE, type);
    values.put(THREAD_ID, threadId);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    long messageId = db.insert(TABLE_NAME, null, values);

    DatabaseFactory.getThreadDatabase(context).update(threadId, true);
    notifyConversationListeners(threadId);
    jobManager.add(new TrimThreadJob(context, threadId));

    if (unread) {
      DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
    }

    return new Pair<>(messageId, threadId);
  }
Exemplo n.º 7
0
 public void deleteConversation(long threadId) {
   DatabaseFactory.getSmsDatabase(context).deleteThread(threadId);
   DatabaseFactory.getMmsDatabase(context).deleteThread(threadId);
   DatabaseFactory.getDraftDatabase(context).clearDrafts(threadId);
   deleteThread(threadId);
   notifyConversationListeners(threadId);
   notifyConversationListListeners();
 }
Exemplo n.º 8
0
 public void deleteConversations(Set<Long> selectedConversations) {
   DatabaseFactory.getSmsDatabase(context).deleteThreads(selectedConversations);
   DatabaseFactory.getMmsDatabase(context).deleteThreads(selectedConversations);
   DatabaseFactory.getDraftDatabase(context).clearDrafts(selectedConversations);
   deleteThreads(selectedConversations);
   notifyConversationListeners(selectedConversations);
   notifyConversationListListeners();
 }
Exemplo n.º 9
0
  public ExptLocatorTree(Genome g) {
    super();
    try {
      java.sql.Connection c = DatabaseFactory.getConnection(ExptLocator.dbRole);
      int species = g.getSpeciesDBID();
      int genome = g.getDBID();

      Statement s = c.createStatement();
      ResultSet rs = null;

      rs =
          s.executeQuery(
              "select e.name, e.version from experiment e, exptToGenome eg where e.active=1 and "
                  + "e.id=eg.experiment and eg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        ChipChipLocator loc = new ChipChipLocator(g, name, version);
        this.addElement(loc.getTreeAddr(), loc);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from rosettaanalysis ra, rosettaToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        MSPLocator msp = new MSPLocator(g, name, version);
        this.addElement(msp.getTreeAddr(), msp);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from bayesanalysis ra, bayesToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name2 = rs.getString(1);
        String version2 = rs.getString(2);
        ExptLocator loc2 = new BayesLocator(g, name2, version2);
        addElement(loc2.getTreeAddr(), loc2);
      }
      rs.close();
      s.close();

      DatabaseFactory.freeConnection(c);
    } catch (SQLException se) {
      se.printStackTrace(System.err);
      throw new RuntimeException(se);
    } catch (UnknownRoleException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 10
0
  public void markIncomingNotificationReceived(long threadId) {
    notifyConversationListeners(threadId);
    DatabaseFactory.getThreadDatabase(context).update(threadId);

    if (org.thoughtcrime.securesms.util.Util.isDefaultSmsProvider(context)) {
      DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
    }

    jobManager.add(new TrimThreadJob(context, threadId));
  }
Exemplo n.º 11
0
  private long getThreadIdFor(IncomingMediaMessage retrieved)
      throws RecipientFormattingException, MmsException {
    if (retrieved.getGroupId() != null) {
      Recipients groupRecipients =
          RecipientFactory.getRecipientsFromString(context, retrieved.getGroupId(), true);
      return DatabaseFactory.getThreadDatabase(context).getThreadIdFor(groupRecipients);
    }

    String localNumber;
    Set<String> group = new HashSet<>();

    if (retrieved.getAddresses().getFrom() == null) {
      throw new MmsException("FROM value in PduHeaders did not exist.");
    }

    group.add(retrieved.getAddresses().getFrom());

    if (TextSecurePreferences.isPushRegistered(context)) {
      localNumber = TextSecurePreferences.getLocalNumber(context);
    } else {
      localNumber = ServiceUtil.getTelephonyManager(context).getLine1Number();
    }

    for (String cc : retrieved.getAddresses().getCc()) {
      PhoneNumberUtil.MatchType match;

      if (localNumber == null) match = PhoneNumberUtil.MatchType.NO_MATCH;
      else match = PhoneNumberUtil.getInstance().isNumberMatch(localNumber, cc);

      if (match == PhoneNumberUtil.MatchType.NO_MATCH
          || match == PhoneNumberUtil.MatchType.NOT_A_NUMBER) {
        group.add(cc);
      }
    }

    if (retrieved.getAddresses().getTo().size() > 1) {
      for (String to : retrieved.getAddresses().getTo()) {
        PhoneNumberUtil.MatchType match;

        if (localNumber == null) match = PhoneNumberUtil.MatchType.NO_MATCH;
        else match = PhoneNumberUtil.getInstance().isNumberMatch(localNumber, to);

        if (match == PhoneNumberUtil.MatchType.NO_MATCH
            || match == PhoneNumberUtil.MatchType.NOT_A_NUMBER) {
          group.add(to);
        }
      }
    }

    String recipientsList = Util.join(group, ",");
    Recipients recipients =
        RecipientFactory.getRecipientsFromString(context, recipientsList, false);

    return DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
  }
Exemplo n.º 12
0
    private EncryptingSmsDatabase.Reader getSmsReader() {
      if (smsReader == null) {
        if (masterSecret.isPresent())
          smsReader =
              DatabaseFactory.getEncryptingSmsDatabase(context)
                  .readerFor(masterSecret.get(), cursor);
        else smsReader = DatabaseFactory.getSmsDatabase(context).readerFor(cursor);
      }

      return smsReader;
    }
Exemplo n.º 13
0
  public void setAllThreadsRead() {
    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    ContentValues contentValues = new ContentValues(1);
    contentValues.put(READ, 1);

    db.update(TABLE_NAME, contentValues, null, null);

    DatabaseFactory.getSmsDatabase(context).setAllMessagesRead();
    DatabaseFactory.getMmsDatabase(context).setAllMessagesRead();
    notifyConversationListListeners();
  }
Exemplo n.º 14
0
 public void close() {
   try {
     basicstmt.close();
     DatabaseFactory.freeConnection(corecxn);
     DatabaseFactory.freeConnection(chipcxn);
     corecxn = null;
     chipcxn = null;
     basicstmt = null;
   } catch (SQLException e) {
     throw new DatabaseException(e.toString(), e);
   }
 }
Exemplo n.º 15
0
  public OutgoingMediaMessage getOutgoingMessage(MasterSecret masterSecret, long messageId)
      throws MmsException, NoSuchMessageException {
    MmsAddressDatabase addr = DatabaseFactory.getMmsAddressDatabase(context);
    AttachmentDatabase attachmentDatabase = DatabaseFactory.getAttachmentDatabase(context);
    Cursor cursor = null;

    try {
      cursor = rawQuery(RAW_ID_WHERE, new String[] {String.valueOf(messageId)});

      if (cursor != null && cursor.moveToNext()) {
        long outboxType = cursor.getLong(cursor.getColumnIndexOrThrow(MESSAGE_BOX));
        String messageText = cursor.getString(cursor.getColumnIndexOrThrow(BODY));
        long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(NORMALIZED_DATE_SENT));
        List<Attachment> attachments =
            new LinkedList<Attachment>(attachmentDatabase.getAttachmentsForMessage(messageId));
        MmsAddresses addresses = addr.getAddressesForId(messageId);
        List<String> destinations = new LinkedList<>();
        String body = getDecryptedBody(masterSecret, messageText, outboxType);

        destinations.addAll(addresses.getBcc());
        destinations.addAll(addresses.getCc());
        destinations.addAll(addresses.getTo());

        Recipients recipients =
            RecipientFactory.getRecipientsFromStrings(context, destinations, false);

        if (body != null && (Types.isGroupQuit(outboxType) || Types.isGroupUpdate(outboxType))) {
          return new OutgoingGroupMediaMessage(recipients, body, attachments, timestamp);
        }

        OutgoingMediaMessage message =
            new OutgoingMediaMessage(
                recipients,
                body,
                attachments,
                timestamp,
                !addresses.getBcc().isEmpty()
                    ? ThreadDatabase.DistributionTypes.BROADCAST
                    : ThreadDatabase.DistributionTypes.DEFAULT);
        if (Types.isSecureType(outboxType)) {
          return new OutgoingSecureMediaMessage(message);
        }

        return message;
      }

      throw new NoSuchMessageException("No record found for id: " + messageId);
    } catch (IOException e) {
      throw new MmsException(e);
    } finally {
      if (cursor != null) cursor.close();
    }
  }
Exemplo n.º 16
0
  public boolean delete(long messageId) {
    long threadId = getThreadIdForMessage(messageId);
    MmsAddressDatabase addrDatabase = DatabaseFactory.getMmsAddressDatabase(context);
    AttachmentDatabase attachmentDatabase = DatabaseFactory.getAttachmentDatabase(context);
    attachmentDatabase.deleteAttachmentsForMessage(messageId);
    addrDatabase.deleteAddressesForId(messageId);

    SQLiteDatabase database = databaseHelper.getWritableDatabase();
    database.delete(TABLE_NAME, ID_WHERE, new String[] {messageId + ""});
    boolean threadDeleted = DatabaseFactory.getThreadDatabase(context).update(threadId);
    notifyConversationListeners(threadId);
    return threadDeleted;
  }
Exemplo n.º 17
0
  private Pair<Long, Long> insertMessageInbox(
      MasterSecretUnion masterSecret,
      IncomingMediaMessage retrieved,
      String contentLocation,
      long threadId,
      long mailbox)
      throws MmsException {
    if (threadId == -1 || retrieved.isGroupMessage()) {
      try {
        threadId = getThreadIdFor(retrieved);
      } catch (RecipientFormattingException e) {
        Log.w("MmsDatabase", e);
        if (threadId == -1) throw new MmsException(e);
      }
    }

    ContentValues contentValues = new ContentValues();

    contentValues.put(DATE_SENT, retrieved.getSentTimeMillis());
    contentValues.put(ADDRESS, retrieved.getAddresses().getFrom());

    contentValues.put(MESSAGE_BOX, mailbox);
    contentValues.put(MESSAGE_TYPE, PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF);
    contentValues.put(THREAD_ID, threadId);
    contentValues.put(CONTENT_LOCATION, contentLocation);
    contentValues.put(STATUS, Status.DOWNLOAD_INITIALIZED);
    contentValues.put(DATE_RECEIVED, generatePduCompatTimestamp());
    contentValues.put(PART_COUNT, retrieved.getAttachments().size());
    contentValues.put(READ, 0);

    if (!contentValues.containsKey(DATE_SENT)) {
      contentValues.put(DATE_SENT, contentValues.getAsLong(DATE_RECEIVED));
    }

    long messageId =
        insertMediaMessage(
            masterSecret,
            retrieved.getAddresses(),
            retrieved.getBody(),
            retrieved.getAttachments(),
            contentValues);

    DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
    DatabaseFactory.getThreadDatabase(context).update(threadId);
    notifyConversationListeners(threadId);
    jobManager.add(new TrimThreadJob(context, threadId));

    return new Pair<>(messageId, threadId);
  }
Exemplo n.º 18
0
  protected long insertMessageOutbox(
      long threadId, OutgoingTextMessage message, long type, boolean forceSms, long date) {
    if (message.isKeyExchange()) type |= Types.KEY_EXCHANGE_BIT;
    else if (message.isSecureMessage()) type |= Types.SECURE_MESSAGE_BIT;
    else if (message.isEndSession()) type |= Types.END_SESSION_BIT;
    if (forceSms) type |= Types.MESSAGE_FORCE_SMS_BIT;

    ContentValues contentValues = new ContentValues(6);
    contentValues.put(
        ADDRESS,
        PhoneNumberUtils.formatNumber(message.getRecipients().getPrimaryRecipient().getNumber()));
    contentValues.put(THREAD_ID, threadId);
    contentValues.put(BODY, message.getMessageBody());
    contentValues.put(DATE_RECEIVED, System.currentTimeMillis());
    contentValues.put(DATE_SENT, date);
    contentValues.put(READ, 1);
    contentValues.put(TYPE, type);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    long messageId = db.insert(TABLE_NAME, ADDRESS, contentValues);

    DatabaseFactory.getThreadDatabase(context).update(threadId, true);
    notifyConversationListeners(threadId);
    jobManager.add(new TrimThreadJob(context, threadId));

    return messageId;
  }
Exemplo n.º 19
0
  private void updateTypeBitmask(long id, long maskOff, long maskOn) {
    Log.w("MessageDatabase", "Updating ID: " + id + " to base type: " + maskOn);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    db.execSQL(
        "UPDATE "
            + TABLE_NAME
            + " SET "
            + TYPE
            + " = ("
            + TYPE
            + " & "
            + (Types.TOTAL_MASK - maskOff)
            + " | "
            + maskOn
            + " )"
            + " WHERE "
            + ID
            + " = ?",
        new String[] {id + ""});

    long threadId = getThreadIdForMessage(id);

    DatabaseFactory.getThreadDatabase(context).update(threadId, false);
    notifyConversationListeners(threadId);
  }
Exemplo n.º 20
0
  public Pair<Long, Long> copyMessageInbox(long messageId) {
    Reader reader = readerFor(getMessage(messageId));
    SmsMessageRecord record = reader.getNext();

    ContentValues contentValues = new ContentValues();
    contentValues.put(TYPE, (record.getType() & ~Types.BASE_TYPE_MASK) | Types.BASE_INBOX_TYPE);
    contentValues.put(ADDRESS, record.getIndividualRecipient().getNumber());
    contentValues.put(ADDRESS_DEVICE_ID, record.getRecipientDeviceId());
    contentValues.put(DATE_RECEIVED, System.currentTimeMillis());
    contentValues.put(DATE_SENT, record.getDateSent());
    contentValues.put(PROTOCOL, 31337);
    contentValues.put(READ, 0);
    contentValues.put(BODY, record.getBody().getBody());
    contentValues.put(THREAD_ID, record.getThreadId());

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    long newMessageId = db.insert(TABLE_NAME, null, contentValues);

    DatabaseFactory.getThreadDatabase(context).update(record.getThreadId(), true);
    notifyConversationListeners(record.getThreadId());

    jobManager.add(new TrimThreadJob(context, record.getThreadId()));
    reader.close();

    return new Pair<>(newMessageId, record.getThreadId());
  }
Exemplo n.º 21
0
/** Simple Factory 방식으로 변경해보았음. */
public class BusinessA {
  // DatabaseFactory 타입의 클래스는 Database 타입의 객체를 생성하도록 구현해야 함
  DatabaseFactory databaseFactory = new DatabaseFactoryImpl();
  // Database 객체 생성을 위임 받은 DatabaseFactory를 통해서 필요로 하는 객체를 취득
  Database db = databaseFactory.getDatabase("mysql");

  // Factory에 의해 구현된 Database 객체는 getConnection() 메서도를 구현하여 Connection 객체를 반환하도록 함
  Connection con = db.getConnection();

  public void insert(String id, String code, int quality) {

    String query = "insert into product values ( " + id + "," + code + "," + quality + ")";
    try {
      Statement stmt = con.createStatement();
      stmt.executeUpdate(query);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public ResultSet selectAll() {
    String query = "select * from product";
    ResultSet resultSet = null;
    try {
      Statement stmt = con.createStatement();
      resultSet = stmt.executeQuery(query);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return resultSet;
  }

  private void writeResultSet(ResultSet resultSet) throws SQLException {
    // ResultSet is initially before the first data set
    while (resultSet.next()) {
      // It is possible to get the columns via name
      // also possible to get the columns via the column number
      // which starts at 1
      // e.g. resultSet.getSTring(2);
      String id = resultSet.getString("id");
      String code = resultSet.getString("code");
      int quality = resultSet.getInt("quality");

      System.out.println("id: " + id + " code: " + code + " quality: " + quality);
    }
  }

  public static void main(String[] argv) {
    BusinessA business = new BusinessA();
    //        business.insert("1", "111", 4);
    //        business.insert("2", "222", 2);
    //        business.insert("3", "333", 3);
    ResultSet resultSet = business.selectAll();
    try {
      business.writeResultSet(resultSet);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}
Exemplo n.º 22
0
  private Pair<Long, Long> updateMessageBodyAndType(
      long messageId, String body, long maskOff, long maskOn) {
    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    db.execSQL(
        "UPDATE "
            + TABLE_NAME
            + " SET "
            + BODY
            + " = ?, "
            + MESSAGE_BOX
            + " = ("
            + MESSAGE_BOX
            + " & "
            + (Types.TOTAL_MASK - maskOff)
            + " | "
            + maskOn
            + ") "
            + "WHERE "
            + ID
            + " = ?",
        new String[] {body, messageId + ""});

    long threadId = getThreadIdForMessage(messageId);

    DatabaseFactory.getThreadDatabase(context).update(threadId);
    notifyConversationListeners(threadId);
    notifyConversationListListeners();

    return new Pair<>(messageId, threadId);
  }
Exemplo n.º 23
0
  public Cursor getFilteredConversationList(List<String> filter) {
    if (filter == null || filter.size() == 0) return null;

    List<Long> rawRecipientIds =
        DatabaseFactory.getAddressDatabase(context).getCanonicalAddressIds(filter);

    if (rawRecipientIds == null || rawRecipientIds.size() == 0) return null;

    SQLiteDatabase db = databaseHelper.getReadableDatabase();
    List<List<Long>> partitionedRecipientIds = Util.partition(rawRecipientIds, 900);
    List<Cursor> cursors = new LinkedList<>();

    for (List<Long> recipientIds : partitionedRecipientIds) {
      String selection = RECIPIENT_IDS + " = ?";
      String[] selectionArgs = new String[recipientIds.size()];

      for (int i = 0; i < recipientIds.size() - 1; i++)
        selection += (" OR " + RECIPIENT_IDS + " = ?");

      int i = 0;
      for (long id : recipientIds) {
        selectionArgs[i++] = String.valueOf(id);
      }

      cursors.add(db.query(TABLE_NAME, null, selection, selectionArgs, null, null, DATE + " DESC"));
    }

    Cursor cursor =
        cursors.size() > 1
            ? new MergeCursor(cursors.toArray(new Cursor[cursors.size()]))
            : cursors.get(0);
    setNotifyConverationListListeners(cursor);
    return cursor;
  }
Exemplo n.º 24
0
    private MmsDatabase.Reader getMmsReader() {
      if (mmsReader == null) {
        mmsReader =
            DatabaseFactory.getMmsDatabase(context).readerFor(masterSecret.orNull(), cursor);
      }

      return mmsReader;
    }
Exemplo n.º 25
0
 public boolean deleteMessage(long messageId) {
   Log.w("MessageDatabase", "Deleting: " + messageId);
   SQLiteDatabase db = databaseHelper.getWritableDatabase();
   long threadId = getThreadIdForMessage(messageId);
   db.delete(TABLE_NAME, ID_WHERE, new String[] {messageId + ""});
   boolean threadDeleted = DatabaseFactory.getThreadDatabase(context).update(threadId, false);
   notifyConversationListeners(threadId);
   return threadDeleted;
 }
Exemplo n.º 26
0
  public void incrementDeliveryReceiptCount(String address, long timestamp) {
    MmsAddressDatabase addressDatabase = DatabaseFactory.getMmsAddressDatabase(context);
    SQLiteDatabase database = databaseHelper.getWritableDatabase();
    Cursor cursor = null;

    try {
      cursor =
          database.query(
              TABLE_NAME,
              new String[] {ID, THREAD_ID, MESSAGE_BOX},
              DATE_SENT + " = ?",
              new String[] {String.valueOf(timestamp)},
              null,
              null,
              null,
              null);

      while (cursor.moveToNext()) {
        if (Types.isOutgoingMessageType(
            cursor.getLong(cursor.getColumnIndexOrThrow(MESSAGE_BOX)))) {
          List<String> addresses =
              addressDatabase.getAddressesListForId(
                  cursor.getLong(cursor.getColumnIndexOrThrow(ID)));

          for (String storedAddress : addresses) {
            try {
              String ourAddress = canonicalizeNumber(context, address);
              String theirAddress = canonicalizeNumberOrGroup(context, storedAddress);

              if (ourAddress.equals(theirAddress) || GroupUtil.isEncodedGroup(theirAddress)) {
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(ID));
                long threadId = cursor.getLong(cursor.getColumnIndexOrThrow(THREAD_ID));

                database.execSQL(
                    "UPDATE "
                        + TABLE_NAME
                        + " SET "
                        + RECEIPT_COUNT
                        + " = "
                        + RECEIPT_COUNT
                        + " + 1 WHERE "
                        + ID
                        + " = ?",
                    new String[] {String.valueOf(id)});

                notifyConversationListeners(threadId);
              }
            } catch (InvalidNumberException e) {
              Log.w("MmsDatabase", e);
            }
          }
        }
      }
    } finally {
      if (cursor != null) cursor.close();
    }
  }
Exemplo n.º 27
0
 private long getThreadIdFor(@NonNull NotificationInd notification) {
   String fromString =
       notification.getFrom() != null && notification.getFrom().getTextString() != null
           ? Util.toIsoString(notification.getFrom().getTextString())
           : "";
   Recipients recipients = RecipientFactory.getRecipientsFromString(context, fromString, false);
   if (recipients.isEmpty())
     recipients =
         RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), false);
   return DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
 }
Exemplo n.º 28
0
  public void updateReadState(long threadId) {
    int unreadCount = DatabaseFactory.getMmsSmsDatabase(context).getUnreadCount(threadId);

    ContentValues contentValues = new ContentValues();
    contentValues.put(READ, unreadCount == 0);

    databaseHelper
        .getWritableDatabase()
        .update(TABLE_NAME, contentValues, ID_WHERE, new String[] {String.valueOf(threadId)});

    notifyConversationListListeners();
  }
Exemplo n.º 29
0
  public void markExpireStarted(long id, long startedAtTimestamp) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(EXPIRE_STARTED, startedAtTimestamp);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    db.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {String.valueOf(id)});

    long threadId = getThreadIdForMessage(id);

    DatabaseFactory.getThreadDatabase(context).update(threadId, false);
    notifyConversationListeners(threadId);
  }
Exemplo n.º 30
0
  public void markStatus(long id, int status) {
    Log.w("MessageDatabase", "Updating ID: " + id + " to status: " + status);
    ContentValues contentValues = new ContentValues();
    contentValues.put(STATUS, status);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    db.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {id + ""});

    long threadId = getThreadIdForMessage(id);
    DatabaseFactory.getThreadDatabase(context).update(threadId, false);
    notifyConversationListeners(threadId);
  }