IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Télécharger un sous repository gihub en zip


Sujet :

JavaScript

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2011
    Messages
    131
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Mars 2011
    Messages : 131
    Points : 49
    Points
    49
    Par défaut Télécharger un sous repository gihub en zip
    Hello,

    je n'y connais pas grand chose en javascript, le script ci dessous permet à partir d'un sous repo github de pouvoir télécharger au format zip le sous repo sur le bureau.
    D'origine github ne permet pas de faire ça.

    Toutefois dans mon cas je souhaiterais à partir du click du bouton de pouvoir télécharger les les fichiers du sous repo dans un répertoire sur mon serveur.

    la demo du script est ici : https://github.com/KinoLien/gitzip/

    Qu'est ce qui faut modifier dans le script pour arriver à cet objectif.

    merci.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
     
      <script type="text/javascript" src="ext/javascript/jszip/jszip.js"></script>
     
     
      <script type="text/javascript">
    		var repoExp = new RegExp("^https://github.com/([^/]+)/([^/]+)(/(tree|blob)/([^/]+)(/(.*))?)?");
     
    		// git_url || url
    		// https://api.github.com/repos/fatcloud/PyCV-time/git/trees/6087888badef7374fd773d6b55739bd4d4e3922a"
    		// https://api.github.com/repos/fatcloud/PyCV-time/git/blobs/4f21b1fc02f3a1dce86813c335ed9cf9298eb19d
    		var _isProcessing = false;
     
    		var clearResults = function(){
    			$("#pathContainer").hide();
    			$("#pathLead").html("");
    			$("#results").html("");
    		};
     
    		var showResults = function(o){
    			generatePathLinks(o);
    			$('#pathContainer').show();
    			_onWindowResize();
    		};
     
    		var load_module = {
    			target: null,
    			isLoading:false,
    			_isForm: false,
    			_cachedClass: [],
    			_loadingClass: ["glyphicon-refresh","glyphicon-refresh-animate"],
    			_defaultTarget: document.getElementById('urlSearch').querySelector(".glyphicon"),
    			loading: function(o){
    				this.isLoading = true;
    				if(o){
    					this._isInCell = o.getAttribute('git-type') == 'cell';
    					if(this._isInCell){
    						this.target = o.parentElement.nextElementSibling.firstChild;
    						this.target.style['display'] = "block";
    					}else{
    						var t = this.target = o.querySelector(".glyphicon") || this._defaultTarget;
    						var list = t.classList;
    						for(var len = list.length; --len > 0;){
    							this._cachedClass.push(list[len]);
    							list.remove(list[len]);
    						}
    						this._loadingClass.forEach(function(item){ list.add(item); });
    					}
    				}
    			},
    			loaded: function(){
    				this.isLoading = false;
    				if(this.target){
    					if(this._isInCell){
    						this.target.style['display'] = "none";
    					}else{
    						var t = this.target;
    						var list = t.classList;
    						for(var len = list.length; --len > 0;)
    							list.remove(list[len]);
    						this._cachedClass.forEach(function(item){ list.add(item); });
    						this._cachedClass = [];
    					}
    				}
    			}
    		};
     
    		GitZip.registerCallback(function(status, message, percent){
    			if(status == 'error' || status == 'done'){
    				if(load_module.isLoading) load_module.loaded();
    			}else{
    				if(!load_module.isLoading) load_module.loading(this);
    			}
    		});
     
    		var zipItButtonClick = function(o){
    			// o.getAttribute('git-url')
    			// o.getAttribute('git-name')
    			var zipName = o.getAttribute('git-name');
    			var url = o.getAttribute('git-url');
    			if(url && !load_module.isLoading){
    				GitZip.zipFromApiUrl(zipName, url, o);
    			}
    		};
    		var getFileButtonClick = function(o){
    			// o.getAttribute('git-url')
    			// var baseUrl = "https://api.github.com/repos/fatcloud/PyCV-time/contents/";
    			var url = o.getAttribute('git-url');
    			if(url && !load_module.isLoading){
    				GitZip.downloadFile(url, o);
    			}
    		};
     
    		var filetrees = [];
    		var contentUrlCollection = [];
    		var processLocked = false;
     
    		var changeDirectoryClick = function(o){
    			var url = o.getAttribute('value');
    			if(url){ renderCells.call(o, url); }
    		};
     
    		var _onWindowResize = function(){
    			var scroll = document.getElementById('scroller');
    			if(scroll) $(scroll).height($(window).height() - scroll.offsetTop);
    		};
     
    		var generatePathLinks = function(resolved){
    			var res = [];
    			var pathSplit = (resolved.path || "").split('/');
    			var showName = "";
    			var outputText = [];
    			var baseUrl = resolved.rootUrl;
    			outputText.push('<a href="#" onclick="changeDirectoryClick(this);" value="'+ baseUrl + '">[root]</a>');
    			while(showName = pathSplit.shift()){
    				res.push(showName);
    				outputText.push('<a href="#" onclick="changeDirectoryClick(this);" value="'+ 
    					[baseUrl, res.join("/")].join("/") + '">'+ showName +'</a>');
    			}
     
    			$('#pathLead').html(outputText.join('/'));
    			return res;
    		};
     
    		var resolveUrl = function(repoUrl){
    			if(typeof repoUrl != 'string') return;
    			var matches = repoUrl.match(repoExp);
    			if(matches && matches.length > 0){
    				var root = (matches[5])? 
    					"https://github.com/" + matches[1] + "/" + matches[2] + "/tree/" + matches[5] :
    					repoUrl;
    				return {
    					author: matches[1],
    					project: matches[2],
    					branch: matches[5],
    					type: matches[4],
    					path: matches[7] || '',
    					inputUrl: repoUrl,
    					rootUrl: root
    				};
    			}
    		};
     
    		var putLogs = function(msg){
    			// console.log(msg);
    			$("#logRegion").append("<p>" + msg + "</p>");
    		};
     
    		var renderCells = function(repoUrl){
     
    			// https://github.com/motephyr/font_20140714
    			// https://api.github.com/repos/fatcloud/PyCV-time/contents/
    			var resolved = resolveUrl(repoUrl);
    			if(!resolved){
    				// invalid url
    				alert("URL is invalid.");
    				return;
    			}
    			if(load_module.isLoading) return;
    			load_module.loading(this);
    			// var contentBaseUrl = ["https://raw.githubusercontent.com", 
    			// 	resolved.author, resolved.project, resolved.branch || ""].join("/");
    			$.ajax({
    			    url: "https://api.github.com/repos/"+ resolved.author + 
    			    	"/" + resolved.project + "/contents/" + resolved.path + 
    			    	(resolved.branch? ("?ref=" + resolved.branch) : ""),
    			    success: function(results) {
    			    	var templateText = '';
    			    	if(!Array.isArray(results)){
    			    		if(results.message) alert("Error: " +  results.message); 
    			    		else{
    			    			var btn = document.getElementById('urlDownload');
    			    			btn.setAttribute('git-url', results.download_url);
    			    			getFileButtonClick(btn);
    			    		};
    			    		return;
    			    	}
    			    	results.sort(function(a,b){
    			    		if(a.type == 'file' && !a.size) return -1;
    			    		if(b.type == 'file' && !b.size) return 1;
    			    		if(a.type == b.type){
    			    			if(a.path < b.path) return -1;
    			    			else if(a.path > b.path) return 1;
    			    			else return 0;
    			    		}else{
    			    			if(a.type == "dir") return -1;
    			    			else return 1;
    			    		}
    			    	});
    			        for(var i = 0, len = results.length; i < len; i++){
    			            var item = results[i],
    			            	valueText = item.path,
    			            	pathText = valueText.split('/').pop(),
    			            	urlText = item.git_url,
    			            	onclickHTML = "", externalLink = false,
    			            	icon, downText, getMethod;
    			            if(item.type == "dir"){
    							icon = '<span class="glyphicon glyphicon-folder-close" aria-hidden="true"></span>';
    							downText = "Download Zip File";
    							getMethod = "zipItButtonClick";
    							onclickHTML = '<a href="#" onclick="changeDirectoryClick(this);" value="' + 
    								item.html_url + '">' + pathText + '</a>';
    								// resolved.rootUrl + "/" + valueText
    			            }else{
    			            	if(item.size){
    			            		icon = '<span class="glyphicon glyphicon-file" aria-hidden="true"></span>';
    								downText = "Get File";
    								getMethod = "getFileButtonClick";
    								onclickHTML = pathText;
    								urlText = item.download_url;
    			            	}else{
    			            		externalLink = true;
    			            		icon = '<span class="glyphicon glyphicon-link" aria-hidden="true"></span>';
    			            		onclickHTML = '<a href="' + item.html_url + '" target="_blank">' + pathText + '</a>';
    			            	}
    			            }
    			            templateText += '<tr><td><div class="table-path">' + icon + onclickHTML + '</div></td>' + 
    		  					'<td>' + (externalLink? "" : 
    		  						('<button type="button" class="btn btn-default" git-name="' + pathText + '" ' +
    		  						'git-url="' + urlText + '" git-type="cell" onclick="'
    		  						+ getMethod + '(this);">' + 
    								'<span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span> '
    								+ downText + '</button>')) + '</td><td>' +
    		  						'<div class="loading"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Loading...</div>'
    								+ '</td></tr>';
    			        }
    			        $('#results').html(templateText);
    			        showResults(resolved);
    			        load_module.loaded();
    			    },
    			    error:function(results){
    			    	putLogs(JSON.stringify(results));
    			    }
    			});
    		};
     
    		$(window).load(function(){
    			var viewHandler = function(e){
    				e.preventDefault();
    				clearResults();
    				renderCells.call(this, $("#urlInput").val());
    			};
    			var submitHandler = function(e){
    				e.preventDefault();
     
    				GitZip.zipRepo($("#urlInput").val(), document.getElementById('urlDownload'));
    			};
    			$(window).on('resize', _onWindowResize);
    			$("#urlForm").on('submit', submitHandler);
    			$("#urlDownload").on('click', submitHandler);
    			$("#urlSearch").on('click', viewHandler);
    		});
     
    	</script>

  2. #2
    Rédacteur/Modérateur

    Avatar de SylvainPV
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    3 375
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 3 375
    Points : 9 944
    Points
    9 944
    Par défaut
    Ce n'est pas faisable en JS côté client. Le navigateur ne peut pas venir écrire des choses sur ton serveur, pour des raisons évidentes de sécurité.

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2011
    Messages
    131
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Mars 2011
    Messages : 131
    Points : 49
    Points
    49
    Par défaut
    merci pour la réponse.

  4. #4
    Expert éminent
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 094
    Points : 6 755
    Points
    6 755
    Par défaut
    J’ai analysé un peu le fonctionnement de GitZip, et en gros il a deux modes de fonctionnement :

    – Le premier, simple, c’est quand on demande la racine du repo. Il accède simplement à l’adresse de zip archivé du repo (par exemple https://github.com/KinoLien/gitzip/archive/master.zip).
    – Le second est plus complexe et fait un ou plusieurs appels à l’API de Github. Ces appels sont possibles en Ajax car Github envoie un en-tête Access-Control-Allow-Origin: *.

    Je crois que le cas qui t’intéresse est le second. Je suis en train d’examiner plus attentivement le code de la bibli (d’ailleurs j’ai trouvé un bug et j’ai proposé un correctif ) pour trouver l’endroit où on peut exploiter le blob reçu, avant qu’il soit converti en zip.

    Une fois ce blob récupéré, tu devrais être en mesure de l’envoyer via Ajax vers ton serveur. Il faudra que tu fasses un script côté serveur pour recevoir le fichier.

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Mars 2011
    Messages
    131
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Mars 2011
    Messages : 131
    Points : 49
    Points
    49
    Par défaut
    Le premier, simple, ==> Oui celui je le maitrise
    le second : ben j'y arrive pas car mon idée est de créer un système de module téléchargeable à partir d'une application. Cela se décompresse dans le temp puis il s'installe.
    L'ajax est intéressant car cela évite le rate limit t évite le rafraichissement de la page.

    Sinon a défaut je vais un repository et je vais mettre les modules à l'intérieur. Donc, je vais me retrouver dans le cas 1. C'est l'orientation que je prends actuellement car plus simple à mon sens.

Discussions similaires

  1. Réponses: 1
    Dernier message: 06/09/2007, 10h59
  2. Télécharger un fichier Zip depuis une adresse internet
    Par jmjmjm dans le forum Web & réseau
    Réponses: 8
    Dernier message: 18/10/2005, 19h12
  3. Zip sous linux
    Par oli2a dans le forum Administration système
    Réponses: 3
    Dernier message: 10/11/2004, 01h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo