<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
    'base/js/dialog',
    'custom/gapi_utils',
    'custom/drive_utils',
], function(IPython, $, utils, dialog, gapi_utils, drive_utils) {
    var Contents = function(options) {
        // Constructor
        //
        // A contentmanager handles passing file operations
        // to the back-end.  This includes checkpointing
        // with the normal file operations.
        //
        // Parameters:
        //  options: dictionary
        //      Dictionary of keyword arguments.
        //          events: $(Events) instance
        //          base_url: string
        var that = this;
        this.events = options.events;
        this.base_url = options.base_url;
    };

    /**
     * Notebook Functions
     */

    /**
     * Load a notebook.
     *
     * Calls success_callback with notebook JSON object (as string), or
     * options.error with error.
     *
     * @method load_notebook
     * @param {String} path
     * @param {String} name
     * @param {Object} options
     */
    Contents.prototype.load = function (path, name, options) {
        gapi_utils.gapi_ready
        .then($.proxy(drive_utils.get_id_for_path, this, path + '/' + name, drive_utils.FileType.FILE))
        .then(function(file_resource) {
            var defer = $.Deferred();
            // Sends request to load file to drive.
            var token = gapi.auth.getToken()['access_token'];
	    var xhrRequest = new XMLHttpRequest();
	    xhrRequest.open('GET', file_resource['downloadUrl'], true);
	    xhrRequest.setRequestHeader('Authorization', 'Bearer ' + token);
	    xhrRequest.onreadystatechange = function(e) {
		if (xhrRequest.readyState == 4) {
		    if (xhrRequest.status == 200) {
			var notebook_contents = xhrRequest.responseText;
			//colab.nbformat.convertJsonNotebookToRealtime(
			//    notebook_contents, model);
        		var model = JSON.parse(notebook_contents);
	    	        defer.resolve({
	 		    content: model,
			    // A hack to deal with file/memory format conversions
			    name: model.metadata.name
			});
		    } else {
			// TODO (wrap xhr as error)
    	               defer.reject();
		    }
		}
	    };
            xhrRequest.send()
            return defer.promise();
        })
        .then(options.success, options.error);
    };

    /**
     * Creates a new file at the specified directory path.
     *
     * @method new
     * @param {String} path The directory in which to create the new file
     * @param {String} name The name of the file to create. Server picks if unspecified.
     * @param {Object} options Includes 'extension' - the extension to use if name not specified.
     */
    Contents.prototype.new = function(path, name, options) {
        var that = this;
        gapi_utils.gapi_ready
        .then($.proxy(drive_utils.get_id_for_path, this, path))
        // TODO: use name or extension if provided
        .then(function(folder_id) {
            return drive_utils.get_new_filename(folder_id)
	    .then(function(filename) {
                var data = {
                    'worksheets': [{
                        'cells' : [{
                            'cell_type': 'code',
                            'input': '',
                            'outputs': [],
                            'language': 'python',
                            'metadata': {}
                        }],
                    }],
                    'metadata': {
                        'name': filename,
                    },
                    'nbformat': 3,
                    'nbformat_minor': 0
                };
                var metadata = {
                    'parents' : [{'id' : folder_id}],
                    'title' : filename,
                    'description': 'IP[y] file',
                    'mimeType': drive_utils.NOTEBOOK_MIMETYPE
                }
                return drive_utils.upload_to_drive(JSON.stringify(data), metadata);
            })
	})
        .then(function(response) {
            return {path: path, name: response['title'] };
        })
        .then(options.success, options.error);
    };

    Contents.prototype.delete_notebook = function(name, path) {
        var settings = {
            processData : false,
            cache : false,
            type : "DELETE",
            dataType : "json",
            success : $.proxy(this.events.trigger, this.events,
                'notebook_deleted.Contents',
                {
                    name: name,
                    path: path
                }),
            error : utils.log_ajax_error
        };
        var url = utils.url_join_encode(
            this.base_url,
            'api/contents',
            path,
            name
        );
        $.ajax(url, settings);<commit_msg>Use $.when for chained promises<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
    'base/js/dialog',
    'custom/gapi_utils',
    'custom/drive_utils',
], function(IPython, $, utils, dialog, gapi_utils, drive_utils) {
    var Contents = function(options) {
        // Constructor
        //
        // A contentmanager handles passing file operations
        // to the back-end.  This includes checkpointing
        // with the normal file operations.
        //
        // Parameters:
        //  options: dictionary
        //      Dictionary of keyword arguments.
        //          events: $(Events) instance
        //          base_url: string
        var that = this;
        this.events = options.events;
        this.base_url = options.base_url;
    };

    /**
     * Notebook Functions
     */

    /**
     * Load a notebook.
     *
     * Calls success_callback with notebook JSON object (as string), or
     * options.error with error.
     *
     * @method load_notebook
     * @param {String} path
     * @param {String} name
     * @param {Object} options
     */
    Contents.prototype.load = function (path, name, options) {
        gapi_utils.gapi_ready
        .then($.proxy(drive_utils.get_id_for_path, this, path + '/' + name, drive_utils.FileType.FILE))
        .then(function(file_resource) {
            var defer = $.Deferred();
            // Sends request to load file to drive.
            var token = gapi.auth.getToken()['access_token'];
	    var xhrRequest = new XMLHttpRequest();
	    xhrRequest.open('GET', file_resource['downloadUrl'], true);
	    xhrRequest.setRequestHeader('Authorization', 'Bearer ' + token);
	    xhrRequest.onreadystatechange = function(e) {
		if (xhrRequest.readyState == 4) {
		    if (xhrRequest.status == 200) {
			var notebook_contents = xhrRequest.responseText;
			//colab.nbformat.convertJsonNotebookToRealtime(
			//    notebook_contents, model);
        		var model = JSON.parse(notebook_contents);
	    	        defer.resolve({
	 		    content: model,
			    // A hack to deal with file/memory format conversions
			    name: model.metadata.name
			});
		    } else {
			// TODO (wrap xhr as error)
    	               defer.reject();
		    }
		}
	    };
            xhrRequest.send()
            return defer.promise();
        })
        .then(options.success, options.error);
    };

    /**
     * Creates a new file at the specified directory path.
     *
     * @method new
     * @param {String} path The directory in which to create the new file
     * @param {String} name The name of the file to create. Server picks if unspecified.
     * @param {Object} options Includes 'extension' - the extension to use if name not specified.
     */
    Contents.prototype.new = function(path, name, options) {
        var folder_id_prm = gapi_utils.gapi_ready
        .then($.proxy(drive_utils.get_id_for_path, this, path))
        // TODO: use name or extension if provided
        var filename_prm = folder_id_prm.then(drive_utils.get_new_filename);
        $.when(folder_id_prm, filename_prm).then(function(folder_id, filename) {
	    var data = {
		'worksheets': [{
		    'cells' : [{
			'cell_type': 'code',
			'input': '',
			'outputs': [],
			'language': 'python',
			'metadata': {}
		    }],
		}],
		'metadata': {
		    'name': filename,
		},
		'nbformat': 3,
		'nbformat_minor': 0
	    };
	    var metadata = {
		'parents' : [{'id' : folder_id}],
		'title' : filename,
		'description': 'IP[y] file',
		'mimeType': drive_utils.NOTEBOOK_MIMETYPE
	    }
	    return drive_utils.upload_to_drive(JSON.stringify(data), metadata);
        })
        .then(function(response) {
            return {path: path, name: response['title'] };
        })
        .then(options.success, options.error);
    };

    Contents.prototype.delete_notebook = function(name, path) {
        var settings = {
            processData : false,
            cache : false,
            type : "DELETE",
            dataType : "json",
            success : $.proxy(this.events.trigger, this.events,
                'notebook_deleted.Contents',
                {
                    name: name,
                    path: path
                }),
            error : utils.log_ajax_error
        };
        var url = utils.url_join_encode(
            this.base_url,
            'api/contents',
            path,
            name
        );
        $.ajax(url, settings);
{'fraction_non_alphanumeric': 0.11730607082630691, 'fraction_numerical': 0.0012647554806070826, 'mean_word_length': 1.7401097314467224, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '816048', 'n_tokens_mistral': 2808, 'n_tokens_neox': 2635, 'n_words': 638}