<commit_before>package org.sugr.gearshift.service;

import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import org.sugr.gearshift.G;
import org.sugr.gearshift.Torrent;
import org.sugr.gearshift.TransmissionData;
import org.sugr.gearshift.TransmissionProfile;
import org.sugr.gearshift.TransmissionSession;
import org.sugr.gearshift.TransmissionSessionManager;
import org.sugr.gearshift.datasource.DataSource;
import org.sugr.gearshift.datasource.TorrentStatus;

import java.io.File;
import java.net.ConnectException;

public class DataService extends IntentService {
    public static final class Requests {
        public static final String GET_SESSION = "get_session";
        public static final String SET_SESSION = "set_session";

        public static final String GET_ALL_TORRENTS = "get_all_torrents";
        public static final String GET_ACTIVE_TORRENTS = "get_active_torrents";
        public static final String ADD_TORRENT = "add_torrent";
        public static final String REMOVE_TORRENT = "remove_torrents";
        public static final String SET_TORRENT = "set_torrent";
        public static final String SET_TORRENT_LOCATION = "set_torrent_location";
        public static final String SET_TORRENT_ACTION = "set_torrent_action";
        public static final String CLEAR_TORRENTS_FOR_PROFILE = "clear_torrents_for_profile";

        public static final String GET_FREE_SPACE = "get_free_space";
        public static final String TEST_PORT = "test_port";
        public static final String UPDATE_BLOCKLIST = "blocklist_update";
    }

    public static final class Args {
        public static final String SESSION = "session";
        public static final String SESSION_FIELDS = "session_fields";
        public static final String DETAIL_FIELDS = "detail_fields";
        public static final String TORRENTS_TO_UPDATE = "torrents_to_update";
        public static final String REMOVE_OBSOLETE = "remove_obsolete";
        public static final String MAGNET_URI = "magnet_uri";
        public static final String TORRENT_DATA = "torrent_data";
        public static final String LOCATION = "location";
        public static final String MOVE_DATA = "move_data";
        public static final String ADD_PAUSED = "add_paused";
        public static final String TEMPORARY_FILE = "temporary_file";
        public static final String DOCUMENT_URI = "document_uri";
        public static final String HASH_STRINGS = "hash_strings";
        public static final String DELETE_DATA = "delete_data";
        public static final String TORRENT_FIELD = "torrent_field";
        public static final String TORRENT_FIELD_VALUE = "torrent_field_value";
        public static final String TORRENT_ACTION = "torrent_action";
    }

    private DataSource dataSource;
    private TransmissionSessionManager manager;
    private TransmissionProfile profile;

    public DataService() {
        super("DataService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String profileId = intent.getStringExtra(G.ARG_PROFILE_ID);
        String requestType = intent.getStringExtra(G.ARG_REQUEST_TYPE);
        Bundle args = intent.getBundleExtra(G.ARG_REQUEST_ARGS);
        Intent response = null;

        if (dataSource == null) {
            dataSource = new DataSource(this);
        }

        dataSource.open();
        try {
            if (requestType == null) {
                throw new IllegalArgumentException("Invalid request type");
            }
            if (profileId == null) {
                throw new IllegalArgumentException("No profile specified");
            } else if (profile == null || !profile.getId().equals(profileId)) {
                profile = new TransmissionProfile(profileId, this);
                if (profile.getHost().equals("")) {
                    throw new IllegalArgumentException("No profile specified");
                }
                if (manager != null) {
                    manager.setProfile(profile);
                }
            }
            if (args == null) {
                throw new IllegalArgumentException("No arguments bundle");
            }

            if (manager == null) {
                manager = new TransmissionSessionManager(this, profile, dataSource);
            }

            if (!manager.hasConnectivity()) {
                throw new ConnectException();
            }

            switch (requestType) {
                case Requests.GET_SESSION:
                    manager.updateSession();
                    response = createResponse(requestType, profileId);
                    break;
                case Requests.SET_SESSION:
                    TransmissionSession session = args.getParcelable(Args.SESSION);
                    String[] keys = args.getStringArray(Args.SESSION_FIELDS);

                    if (session == null) {
                        throw new IllegalArgumentException("No session object given");
                    }
                    if (keys == null || keys.length == 0) {
                        throw new IllegalArgumentException("No session fields given");
                    }

                    manager.setSession(session, keys);
                    response = createResponse(requestType, profileId);
                    break;
                case Requests.GET_ALL_TORRENTS:
                case Requests.GET_ACTIVE_TORRENTS: {
                    TorrentStatus status;
                    String[] fields = Torrent.Fields.STATS;

                    if (!dataSource.hasCompleteMetadata()) {
                        fields = G.concat(Torrent.Fields.METADATA, fields);
                    }

                    if (args.getBoolean(Args.DETAIL_FIELDS, false)) {
                        fields = G.concat(fields, Torrent.Fields.STATS_EXTRA);
                        if (!dataSource.hasExtraInfo()) {
                            fields = G.concat(fields, Torrent.Fields.INFO_EXTRA);
                        }
                    }

                    String[] hashStrings = args.getStringArray(Args.TORRENTS_TO_UPDATE);
                    if (hashStrings != null) {
                        status = manager.getTorrents(fields, hashStrings, false);
                    } else if (requestType.equals(Requests.GET_ACTIVE_TORRENTS)
                        && !args.getBoolean(Args.DETAIL_FIELDS, false)) {
                        status = manager.getActiveTorrents(fields);
                    } else {
                        status = manager.getTorrents(fields, null,
                            args.getBoolean(Args.REMOVE_OBSOLETE, false));
                    }

                    String[] unnamed = dataSource.getUnnamedTorrentHashStrings();
                    if (unnamed != null && unnamed.length > 0) {
                        manager.getTorrents(
                            G.concat(new String[]{Torrent.Fields.hashString}, Torrent.Fields.METADATA),
                            unnamed, false);
                    }

                    response = createResponse(requestType, profileId)
                        .putExtra(G.ARG_ADDED, status.hasAdded)
                        .putExtra(G.ARG_REMOVED, status.hasRemoved)
                        .putExtra(G.ARG_STATUS_CHANGED, status.hasStatusChanged)
                        .putExtra(G.ARG_INCOMPLETE_METADATA, status.hasIncompleteMetadata);
                    break;
                }
                case Requests.ADD_TORRENT: {
                    String uri = args.getString(Args.MAGNET_URI);
                    String data = args.getString(Args.TORRENT_DATA);
                    String location = args.getString(Args.LOCATION);
                    boolean paused = args.getBoolean(Args.ADD_PAUSED, false);
                    String temporary = args.getString(Args.TEMPORARY_FILE);
                    Uri document = args.getParcelable(Args.DOCUMENT_URI);

                    if (TextUtils.isEmpty(uri) && TextUtils.isEmpty(data)) {
                        throw new IllegalArgumentException(
                            "Either a uri or the torrent data needs to be specified");
                    }

                    String addedHash = manager.addTorrent(uri, data, location, paused);

                    if (!TextUtils.isEmpty(temporary)) {
                        File file = new File(temporary);
                        if (!file.delete()) {
                            G.logD("Couldn't remove torrent " + file.getName());
                        }
                    }
                    if (document != null) {
                        if (!DocumentsContract.deleteDocument(getContentResolver(), document)) {
                            G.logD("Couldn't remove torrent " + document.toString());
                        }
                    }

                    response = createResponse(requestType, profileId)
                        .putExtra(G.ARG_ADDED_HASH, addedHash);
                    break;
                }
                case Requests.REMOVE_TORRENT: {
                    String[] hashStrings = args.getStringArray(Args.HASH_STRINGS);
                    boolean delete = args.getBoolean(Args.DELETE_DATA, false);

                    if (hashStrings == null || hashStrings.length == 0) {
                        throw new IllegalArgumentException("No hash strings provided");
                    }

                    manager.removeTorrent(hashStrings, delete);
                    response = createResponse(requestType, profileId);
                    break;
                }
                case Requests.SET_TORRENT: {
                    String[] hashStrings = args.getStringArray(Args.HASH_STRINGS);
                    String field = args.getString(Args.TORRENT_FIELD);<commit_msg>put an api guard against the new api usage<commit_after>package org.sugr.gearshift.service;

import android.annotation.TargetApi;
import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import org.sugr.gearshift.G;
import org.sugr.gearshift.Torrent;
import org.sugr.gearshift.TransmissionData;
import org.sugr.gearshift.TransmissionProfile;
import org.sugr.gearshift.TransmissionSession;
import org.sugr.gearshift.TransmissionSessionManager;
import org.sugr.gearshift.datasource.DataSource;
import org.sugr.gearshift.datasource.TorrentStatus;

import java.io.File;
import java.net.ConnectException;

public class DataService extends IntentService {
    public static final class Requests {
        public static final String GET_SESSION = "get_session";
        public static final String SET_SESSION = "set_session";

        public static final String GET_ALL_TORRENTS = "get_all_torrents";
        public static final String GET_ACTIVE_TORRENTS = "get_active_torrents";
        public static final String ADD_TORRENT = "add_torrent";
        public static final String REMOVE_TORRENT = "remove_torrents";
        public static final String SET_TORRENT = "set_torrent";
        public static final String SET_TORRENT_LOCATION = "set_torrent_location";
        public static final String SET_TORRENT_ACTION = "set_torrent_action";
        public static final String CLEAR_TORRENTS_FOR_PROFILE = "clear_torrents_for_profile";

        public static final String GET_FREE_SPACE = "get_free_space";
        public static final String TEST_PORT = "test_port";
        public static final String UPDATE_BLOCKLIST = "blocklist_update";
    }

    public static final class Args {
        public static final String SESSION = "session";
        public static final String SESSION_FIELDS = "session_fields";
        public static final String DETAIL_FIELDS = "detail_fields";
        public static final String TORRENTS_TO_UPDATE = "torrents_to_update";
        public static final String REMOVE_OBSOLETE = "remove_obsolete";
        public static final String MAGNET_URI = "magnet_uri";
        public static final String TORRENT_DATA = "torrent_data";
        public static final String LOCATION = "location";
        public static final String MOVE_DATA = "move_data";
        public static final String ADD_PAUSED = "add_paused";
        public static final String TEMPORARY_FILE = "temporary_file";
        public static final String DOCUMENT_URI = "document_uri";
        public static final String HASH_STRINGS = "hash_strings";
        public static final String DELETE_DATA = "delete_data";
        public static final String TORRENT_FIELD = "torrent_field";
        public static final String TORRENT_FIELD_VALUE = "torrent_field_value";
        public static final String TORRENT_ACTION = "torrent_action";
    }

    private DataSource dataSource;
    private TransmissionSessionManager manager;
    private TransmissionProfile profile;

    public DataService() {
        super("DataService");
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onHandleIntent(Intent intent) {
        String profileId = intent.getStringExtra(G.ARG_PROFILE_ID);
        String requestType = intent.getStringExtra(G.ARG_REQUEST_TYPE);
        Bundle args = intent.getBundleExtra(G.ARG_REQUEST_ARGS);
        Intent response = null;

        if (dataSource == null) {
            dataSource = new DataSource(this);
        }

        dataSource.open();
        try {
            if (requestType == null) {
                throw new IllegalArgumentException("Invalid request type");
            }
            if (profileId == null) {
                throw new IllegalArgumentException("No profile specified");
            } else if (profile == null || !profile.getId().equals(profileId)) {
                profile = new TransmissionProfile(profileId, this);
                if (profile.getHost().equals("")) {
                    throw new IllegalArgumentException("No profile specified");
                }
                if (manager != null) {
                    manager.setProfile(profile);
                }
            }
            if (args == null) {
                throw new IllegalArgumentException("No arguments bundle");
            }

            if (manager == null) {
                manager = new TransmissionSessionManager(this, profile, dataSource);
            }

            if (!manager.hasConnectivity()) {
                throw new ConnectException();
            }

            switch (requestType) {
                case Requests.GET_SESSION:
                    manager.updateSession();
                    response = createResponse(requestType, profileId);
                    break;
                case Requests.SET_SESSION:
                    TransmissionSession session = args.getParcelable(Args.SESSION);
                    String[] keys = args.getStringArray(Args.SESSION_FIELDS);

                    if (session == null) {
                        throw new IllegalArgumentException("No session object given");
                    }
                    if (keys == null || keys.length == 0) {
                        throw new IllegalArgumentException("No session fields given");
                    }

                    manager.setSession(session, keys);
                    response = createResponse(requestType, profileId);
                    break;
                case Requests.GET_ALL_TORRENTS:
                case Requests.GET_ACTIVE_TORRENTS: {
                    TorrentStatus status;
                    String[] fields = Torrent.Fields.STATS;

                    if (!dataSource.hasCompleteMetadata()) {
                        fields = G.concat(Torrent.Fields.METADATA, fields);
                    }

                    if (args.getBoolean(Args.DETAIL_FIELDS, false)) {
                        fields = G.concat(fields, Torrent.Fields.STATS_EXTRA);
                        if (!dataSource.hasExtraInfo()) {
                            fields = G.concat(fields, Torrent.Fields.INFO_EXTRA);
                        }
                    }

                    String[] hashStrings = args.getStringArray(Args.TORRENTS_TO_UPDATE);
                    if (hashStrings != null) {
                        status = manager.getTorrents(fields, hashStrings, false);
                    } else if (requestType.equals(Requests.GET_ACTIVE_TORRENTS)
                        && !args.getBoolean(Args.DETAIL_FIELDS, false)) {
                        status = manager.getActiveTorrents(fields);
                    } else {
                        status = manager.getTorrents(fields, null,
                            args.getBoolean(Args.REMOVE_OBSOLETE, false));
                    }

                    String[] unnamed = dataSource.getUnnamedTorrentHashStrings();
                    if (unnamed != null && unnamed.length > 0) {
                        manager.getTorrents(
                            G.concat(new String[]{Torrent.Fields.hashString}, Torrent.Fields.METADATA),
                            unnamed, false);
                    }

                    response = createResponse(requestType, profileId)
                        .putExtra(G.ARG_ADDED, status.hasAdded)
                        .putExtra(G.ARG_REMOVED, status.hasRemoved)
                        .putExtra(G.ARG_STATUS_CHANGED, status.hasStatusChanged)
                        .putExtra(G.ARG_INCOMPLETE_METADATA, status.hasIncompleteMetadata);
                    break;
                }
                case Requests.ADD_TORRENT: {
                    String uri = args.getString(Args.MAGNET_URI);
                    String data = args.getString(Args.TORRENT_DATA);
                    String location = args.getString(Args.LOCATION);
                    boolean paused = args.getBoolean(Args.ADD_PAUSED, false);
                    String temporary = args.getString(Args.TEMPORARY_FILE);
                    Uri document = args.getParcelable(Args.DOCUMENT_URI);

                    if (TextUtils.isEmpty(uri) && TextUtils.isEmpty(data)) {
                        throw new IllegalArgumentException(
                            "Either a uri or the torrent data needs to be specified");
                    }

                    String addedHash = manager.addTorrent(uri, data, location, paused);

                    if (!TextUtils.isEmpty(temporary)) {
                        File file = new File(temporary);
                        if (!file.delete()) {
                            G.logD("Couldn't remove torrent " + file.getName());
                        }
                    }
                    if (document != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        if (!DocumentsContract.deleteDocument(getContentResolver(), document)) {
                            G.logD("Couldn't remove torrent " + document.toString());
                        }
                    }

                    response = createResponse(requestType, profileId)
                        .putExtra(G.ARG_ADDED_HASH, addedHash);
                    break;
                }
                case Requests.REMOVE_TORRENT: {
                    String[] hashStrings = args.getStringArray(Args.HASH_STRINGS);
                    boolean delete = args.getBoolean(Args.DELETE_DATA, false);

                    if (hashStrings == null || hashStrings.length == 0) {
                        throw new IllegalArgumentException("No hash strings provided");
                    }

                    manager.removeTorrent(hashStrings, delete);
                    response = createResponse(requestType, profileId);
                    break;
                }
                case Requests.SET_TORRENT: {
                    String[] hashStrings = args.getStringArray(Args.HASH_STRINGS);
                    String field = args.getString(Args.TORRENT_FIELD);
{'fraction_non_alphanumeric': 0.08062347492654748, 'fraction_numerical': 0.0003983865345351327, 'mean_word_length': 1.8181307886612406, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1219085', 'n_tokens_mistral': 5103, 'n_tokens_neox': 4741, 'n_words': 1110}