Search in sources :

Example 1 with MimeTypeMap

use of android.webkit.MimeTypeMap in project qksms by moezbhatti.

the class UriImage method initFromFile.

private void initFromFile(Context context, Uri uri) {
    mPath = uri.getPath();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String extension = MimeTypeMap.getFileExtensionFromUrl(mPath);
    if (TextUtils.isEmpty(extension)) {
        // getMimeTypeFromExtension() doesn't handle spaces in filenames nor can it handle
        // urlEncoded strings. Let's try one last time at finding the extension.
        int dotPos = mPath.lastIndexOf('.');
        if (0 <= dotPos) {
            extension = mPath.substring(dotPos + 1);
        }
    }
    mContentType = mimeTypeMap.getMimeTypeFromExtension(extension);
    // It's ok if mContentType is null. Eventually we'll show a toast telling the
    // user the picture couldn't be attached.
    buildSrcFromPath();
}
Also used : MimeTypeMap(android.webkit.MimeTypeMap)

Example 2 with MimeTypeMap

use of android.webkit.MimeTypeMap in project Signal-Android by WhisperSystems.

the class SaveAttachmentTask method constructOutputFile.

private File constructOutputFile(String contentType, long timestamp) throws IOException {
    File sdCard = Environment.getExternalStorageDirectory();
    File outputDirectory;
    if (contentType.startsWith("video/")) {
        outputDirectory = new File(sdCard.getAbsoluteFile() + File.separator + Environment.DIRECTORY_MOVIES);
    } else if (contentType.startsWith("audio/")) {
        outputDirectory = new File(sdCard.getAbsolutePath() + File.separator + Environment.DIRECTORY_MUSIC);
    } else if (contentType.startsWith("image/")) {
        outputDirectory = new File(sdCard.getAbsolutePath() + File.separator + Environment.DIRECTORY_PICTURES);
    } else {
        outputDirectory = new File(sdCard.getAbsolutePath() + File.separator + Environment.DIRECTORY_DOWNLOADS);
    }
    if (!outputDirectory.mkdirs())
        Log.w(TAG, "mkdirs() returned false, attempting to continue");
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String extension = mimeTypeMap.getExtensionFromMimeType(contentType);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
    String base = "signal-" + dateFormatter.format(timestamp);
    if (extension == null)
        extension = "attach";
    int i = 0;
    File file = new File(outputDirectory, base + "." + extension);
    while (file.exists()) {
        file = new File(outputDirectory, base + "-" + (++i) + "." + extension);
    }
    return file;
}
Also used : MimeTypeMap(android.webkit.MimeTypeMap) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with MimeTypeMap

use of android.webkit.MimeTypeMap in project material-dialogs by afollestad.

the class FileChooserDialog method listFiles.

File[] listFiles(@Nullable String mimeType, @Nullable String[] extensions) {
    File[] contents = parentFolder.listFiles();
    List<File> results = new ArrayList<>();
    if (contents != null) {
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        for (File fi : contents) {
            if (fi.isDirectory()) {
                results.add(fi);
            } else {
                if (extensions != null) {
                    boolean found = false;
                    for (String ext : extensions) {
                        if (fi.getName().toLowerCase().endsWith(ext.toLowerCase())) {
                            found = true;
                            break;
                        }
                    }
                    if (found) {
                        results.add(fi);
                    }
                } else if (mimeType != null) {
                    if (fileIsMimeType(fi, mimeType, mimeTypeMap)) {
                        results.add(fi);
                    }
                }
            }
        }
        Collections.sort(results, new FileSorter());
        return results.toArray(new File[results.size()]);
    }
    return null;
}
Also used : ArrayList(java.util.ArrayList) MimeTypeMap(android.webkit.MimeTypeMap) File(java.io.File)

Example 4 with MimeTypeMap

use of android.webkit.MimeTypeMap in project Tusky by Vavassor.

the class ComposeActivity method uploadMedia.

private void uploadMedia(final QueuedMedia item) {
    item.readyStage = QueuedMedia.ReadyStage.UPLOADING;
    final String mimeType = getContentResolver().getType(item.uri);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String fileExtension = map.getExtensionFromMimeType(mimeType);
    final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name), String.valueOf(new Date().getTime()), randomAlphanumericString(10), fileExtension);
    byte[] content = item.content;
    if (content == null) {
        InputStream stream;
        try {
            stream = getContentResolver().openInputStream(item.uri);
        } catch (FileNotFoundException e) {
            Log.d(TAG, Log.getStackTraceString(e));
            return;
        }
        content = inputStreamGetBytes(stream);
        IOUtils.closeQuietly(stream);
        if (content == null) {
            return;
        }
    }
    RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), content);
    MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile);
    item.uploadRequest = mastodonAPI.uploadMedia(body);
    item.uploadRequest.enqueue(new Callback<Media>() {

        @Override
        public void onResponse(Call<Media> call, retrofit2.Response<Media> response) {
            if (response.isSuccessful()) {
                onUploadSuccess(item, response.body());
            } else {
                Log.d(TAG, "Upload request failed. " + response.message());
                onUploadFailure(item, call.isCanceled());
            }
        }

        @Override
        public void onFailure(Call<Media> call, Throwable t) {
            Log.d(TAG, t.getMessage());
            onUploadFailure(item, false);
        }
    });
}
Also used : InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) Media(com.keylesspalace.tusky.entity.Media) StringUtils.randomAlphanumericString(com.keylesspalace.tusky.util.StringUtils.randomAlphanumericString) MimeTypeMap(android.webkit.MimeTypeMap) Date(java.util.Date) MultipartBody(okhttp3.MultipartBody) RequestBody(okhttp3.RequestBody)

Example 5 with MimeTypeMap

use of android.webkit.MimeTypeMap in project ETSMobile-Android2 by ApplETS.

the class MoodleCourseDetailsFragment method onRequestSuccess.

@Override
public void onRequestSuccess(Object o) {
    if (o instanceof MoodleCoreCourses) {
        MoodleCoreCourses moodleCoreCourses = (MoodleCoreCourses) o;
        // create empty data
        listDataSectionName = new HashMap<HeaderText, Object[]>();
        listDataHeader = new ArrayList<HeaderText>();
        int positionSection = 0;
        for (MoodleCoreCourse coreCourse : moodleCoreCourses) {
            listMoodleLinkModules = new ArrayList<MoodleCoreModule>();
            listMoodleResourceContents = new ArrayList<MoodleModuleContent>();
            for (MoodleCoreModule coreModule : coreCourse.getModules()) {
                if (coreModule.getModname().equals("folder")) {
                    if (coreModule.getContents() != null)
                        listMoodleResourceContents.addAll(coreModule.getContents());
                } else if (coreModule.getModname().equals("url") || coreModule.getModname().equals("forum")) {
                    listMoodleLinkModules.add(coreModule);
                } else if (coreModule.getModname().equals("resource")) {
                    listMoodleResourceContents.addAll(coreModule.getContents());
                }
            }
            Object[] finalArray = ArrayUtils.addAll(listMoodleLinkModules.toArray(), listMoodleResourceContents.toArray());
            if (finalArray.length != 0)
                listDataSectionName.put(new HeaderText(coreCourse.getName(), positionSection), finalArray);
            positionSection++;
        }
        listDataHeader.addAll(listDataSectionName.keySet());
        Collections.sort(listDataHeader, new Comparator<HeaderText>() {

            @Override
            public int compare(HeaderText headerText1, HeaderText headerText2) {
                if (headerText1.getPosition() < headerText2.getPosition()) {
                    return -1;
                } else if (headerText1.getPosition() == headerText2.getPosition()) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        expandableListMoodleAdapter = new ExpandableListMoodleSectionAdapter(getActivity(), listDataHeader, listDataSectionName);
        expListView.setAdapter(expandableListMoodleAdapter);
        expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Object object = expandableListMoodleAdapter.getChild(groupPosition, childPosition);
                if (object instanceof MoodleModuleContent) {
                    MoodleModuleContent item = (MoodleModuleContent) object;
                    String url = item.getFileurl() + "&token=" + ApplicationManager.userCredentials.getMoodleToken();
                    Uri uri = Uri.parse(url);
                    DownloadManager.Request request = new DownloadManager.Request(uri);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, item.getFilename());
                    //                      r.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    MimeTypeMap mimetype = MimeTypeMap.getSingleton();
                    String extension = FilenameUtils.getExtension(item.getFilename());
                    request.setMimeType(mimetype.getMimeTypeFromExtension(extension));
                    dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                    enqueue = dm.enqueue(request);
                    AnalyticsHelper.getInstance(getActivity()).sendActionEvent(getClass().getSimpleName(), TELECHARGE_FICHIER_MOODLE);
                }
                if (object instanceof MoodleCoreModule) {
                    MoodleCoreModule item = (MoodleCoreModule) object;
                    String url = "";
                    if (item.getModname().equals("url")) {
                        url = item.getContents().get(0).getFileurl();
                    } else {
                        url = item.getUrl();
                    }
                    AnalyticsHelper.getInstance(getActivity()).sendActionEvent(getClass().getSimpleName(), CONSULTE_PAGE_MOODLE);
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                }
                return true;
            }
        });
        super.onRequestSuccess(null);
    }
}
Also used : MimeTypeMap(android.webkit.MimeTypeMap) Uri(android.net.Uri) DownloadManager(android.app.DownloadManager) MoodleModuleContent(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleModuleContent) ExpandableListMoodleSectionAdapter(ca.etsmtl.applets.etsmobile.ui.adapter.ExpandableListMoodleSectionAdapter) ExpandableListView(android.widget.ExpandableListView) MoodleCoreModule(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCoreModule) MoodleCoreCourse(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCoreCourse) MoodleCoreCourses(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCoreCourses) SpringAndroidSpiceRequest(com.octo.android.robospice.request.springandroid.SpringAndroidSpiceRequest) Intent(android.content.Intent) View(android.view.View) ExpandableListView(android.widget.ExpandableListView)

Aggregations

MimeTypeMap (android.webkit.MimeTypeMap)51 File (java.io.File)12 Intent (android.content.Intent)7 DownloadManager (android.app.DownloadManager)6 Uri (android.net.Uri)6 SimpleDateFormat (java.text.SimpleDateFormat)4 ArrayList (java.util.ArrayList)4 SuppressLint (android.annotation.SuppressLint)3 ActivityNotFoundException (android.content.ActivityNotFoundException)3 ResolveInfo (android.content.pm.ResolveInfo)3 FileNotFoundException (java.io.FileNotFoundException)3 IOException (java.io.IOException)3 Date (java.util.Date)3 IntentFilter (android.content.IntentFilter)2 Cursor (android.database.Cursor)2 View (android.view.View)2 InputStream (java.io.InputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 MultipartBody (okhttp3.MultipartBody)2