CCMain.m 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate>
  37. {
  38. tableMetadata *_metadata;
  39. BOOL _isRoot;
  40. BOOL _isViewDidLoad;
  41. BOOL _isOfflineServerUrl;
  42. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. UIImageView *_ImageTitleHomeCryptoCloud;
  48. UIView *_reMenuBackgroundView;
  49. UITapGestureRecognizer *_singleFingerTap;
  50. NSString *_directoryGroupBy;
  51. NSString *_directoryOrder;
  52. NSUInteger _failedAttempts;
  53. NSDate *_lockUntilDate;
  54. NSString *_fatherPermission;
  55. UIRefreshControl *_refreshControl;
  56. UIDocumentInteractionController *_docController;
  57. CCHud *_hud;
  58. CCHud *_hudDeterminate;
  59. // Datasource
  60. CCSectionDataSourceMetadata *_sectionDataSource;
  61. NSDate *_dateReadDataSource;
  62. // Search
  63. BOOL _isSearchMode;
  64. NSString *_searchFileName;
  65. NSMutableArray *_searchResultMetadatas;
  66. NSString *_depth;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. BOOL _loadingFolder;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  104. _queueSelector = [NSMutableArray new];
  105. _sectionDataSource = [CCSectionDataSourceMetadata new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _depth = @"infinity";
  112. _noFilesSearchTitle = @"";
  113. _noFilesSearchDescription = @"";
  114. // delegate
  115. self.tableView.delegate = self;
  116. self.tableView.tableFooterView = [UIView new];
  117. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  118. self.tableView.emptyDataSetDelegate = self;
  119. self.tableView.emptyDataSetSource = self;
  120. self.searchController.delegate = self;
  121. self.searchController.searchBar.delegate = self;
  122. [[CCNetworking sharedNetworking] settingDelegate:self];
  123. // Custom Cell
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  126. // long press recognizer TableView
  127. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  128. [self.tableView addGestureRecognizer:longPressRecognizer];
  129. // Pull-to-Refresh
  130. [self createRefreshControl];
  131. // Register for 3D Touch Previewing if available
  132. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  133. {
  134. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  135. }
  136. // Back Button
  137. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  138. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  139. // reMenu Background
  140. _reMenuBackgroundView = [[UIView alloc] init];
  141. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  142. // if this is not Main (the Main uses inizializeMain)
  143. if (_isRoot == NO && app.activeAccount.length > 0) {
  144. // Settings this folder & delegate & Loading datasource
  145. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  146. // Load Datasource
  147. [self reloadDatasource:_serverUrl];
  148. // Read (File) Folder
  149. [self readFileReloadFolder];
  150. }
  151. // Title
  152. [self setTitle];
  153. // Search
  154. self.definesPresentationContext = YES;
  155. self.searchController.searchResultsUpdater = self;
  156. self.searchController.dimsBackgroundDuringPresentation = NO;
  157. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  158. [self.searchController.searchBar sizeToFit];
  159. self.searchController.searchBar.delegate = self;
  160. // Hide Search Filed on Load
  161. self.tableView.tableHeaderView = self.searchController.searchBar;
  162. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  163. }
  164. // Apparirà
  165. - (void)viewWillAppear:(BOOL)animated
  166. {
  167. [super viewWillAppear:animated];
  168. // test
  169. if (app.activeAccount.length == 0)
  170. return;
  171. // Settings this folder & delegate & Loading datasource
  172. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  173. [[CCNetworking sharedNetworking] settingDelegate:self];
  174. // Color
  175. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  176. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  177. if (_isSelectedMode)
  178. [self setUINavigationBarSelected];
  179. else
  180. [self setUINavigationBarDefault];
  181. // If not editing mode remove _selectedFileIDs
  182. if (!self.tableView.editing)
  183. [_selectedFileIDsMetadatas removeAllObjects];
  184. // Plus Button
  185. [app plusButtonVisibile:true];
  186. }
  187. // E' arrivato
  188. - (void)viewDidAppear:(BOOL)animated
  189. {
  190. [super viewDidAppear:animated];
  191. // Test viewDidLoad
  192. if (_isViewDidLoad) {
  193. _isViewDidLoad = NO;
  194. } else {
  195. if (app.activeAccount.length > 0 && app.activeMain != self) {
  196. // Load Datasource
  197. [self reloadDatasource:_serverUrl];
  198. // Read (file) Folder
  199. [self readFileReloadFolder];
  200. }
  201. }
  202. // Active Main
  203. app.activeMain = self;
  204. // Title
  205. [self setTitle];
  206. }
  207. - (void)viewWillDisappear:(BOOL)animated
  208. {
  209. [super viewWillDisappear:animated];
  210. [self closeAllMenu];
  211. }
  212. - (void)didReceiveMemoryWarning
  213. {
  214. [super didReceiveMemoryWarning];
  215. // Dispose of any resources that can be recreated.
  216. }
  217. - (BOOL)prefersStatusBarHidden
  218. {
  219. return NO;
  220. }
  221. // detect scroll for remove keyboard in search mode
  222. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  223. {
  224. if (_isSearchMode && scrollView == self.tableView) {
  225. [self.searchController.searchBar endEditing:YES];
  226. }
  227. }
  228. - (void)changeTheming
  229. {
  230. if (self.isViewLoaded && self.view.window)
  231. [app changeTheming:self];
  232. // Refresh control
  233. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  234. // Reload Table View
  235. [self tableViewReloadData];
  236. }
  237. #pragma --------------------------------------------------------------------------------------------
  238. #pragma mark ===== Initizlize Mail =====
  239. #pragma --------------------------------------------------------------------------------------------
  240. - (void)initializeMain:(NSNotification *)notification
  241. {
  242. _directoryGroupBy = nil;
  243. _directoryOrder = nil;
  244. _dateReadDataSource = nil;
  245. // test
  246. if (app.activeAccount.length == 0)
  247. return;
  248. if ([app.listMainVC count] == 0 || _isRoot) {
  249. // This is Root
  250. _isRoot = YES;
  251. // Crypto Mode
  252. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  253. app.isCryptoCloudMode = NO;
  254. } else {
  255. app.isCryptoCloudMode = YES;
  256. }
  257. // go Home
  258. [self.navigationController popToRootViewControllerAnimated:NO];
  259. // Remove search mode
  260. [self cancelSearchBar];
  261. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  262. _isFolderEncrypted = NO;
  263. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  264. // add list
  265. [app.listMainVC setObject:self forKey:_serverUrl];
  266. // setting Networking
  267. [[CCNetworking sharedNetworking] settingDelegate:self];
  268. [[CCNetworking sharedNetworking] settingAccount];
  269. // populate shared Link & User variable
  270. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  271. if (results) {
  272. app.sharesLink = results[0];
  273. app.sharesUserAndGroup = results[1];
  274. }
  275. // Setting Theming
  276. [app settingThemingColorBrand];
  277. // Load Datasource
  278. [self reloadDatasource:_serverUrl];
  279. // Read (File) Folder
  280. [self readFileReloadFolder];
  281. // Load photo datasorce
  282. if (app.activePhotos)
  283. [app.activePhotos reloadDatasourceForced];
  284. // remove all of detail
  285. if (app.activeDetail)
  286. [app.activeDetail removeAllView];
  287. // remove all Notification Messages
  288. [app.listOfNotifications removeAllObjects];
  289. // home main
  290. app.homeMain = self;
  291. // Initializations
  292. [app applicationInitialized];
  293. } else {
  294. // reload datasource
  295. [self reloadDatasource:_serverUrl];
  296. }
  297. }
  298. #pragma --------------------------------------------------------------------------------------------
  299. #pragma mark ==== DZNEmptyDataSetSource ====
  300. #pragma --------------------------------------------------------------------------------------------
  301. /*
  302. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  303. {
  304. if(_isSearchMode)
  305. return NO;
  306. else
  307. return YES;
  308. }
  309. */
  310. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  311. {
  312. if (_loadingFolder)
  313. return NO;
  314. else
  315. return YES;
  316. }
  317. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  318. {
  319. return [UIColor whiteColor];
  320. }
  321. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  322. {
  323. if (_isSearchMode)
  324. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  325. else
  326. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  327. }
  328. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  329. {
  330. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  331. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  332. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  333. activityView.color = [NCBrandColor sharedInstance].brand;
  334. [activityView startAnimating];
  335. return activityView;
  336. }
  337. return nil;
  338. }
  339. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  340. {
  341. NSString *text;
  342. if (_isSearchMode) {
  343. text = _noFilesSearchTitle;
  344. } else {
  345. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  346. }
  347. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  348. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  349. }
  350. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  351. {
  352. NSString *text;
  353. if (_isSearchMode) {
  354. text = _noFilesSearchDescription;
  355. } else {
  356. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  357. }
  358. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  359. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  360. paragraph.alignment = NSTextAlignmentCenter;
  361. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  362. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  363. }
  364. #pragma --------------------------------------------------------------------------------------------
  365. #pragma mark ===== Text Field =====
  366. #pragma --------------------------------------------------------------------------------------------
  367. - (void)minCharTextFieldDidChange:(UITextField *)sender
  368. {
  369. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  370. if (alertController)
  371. {
  372. UITextField *fileName = alertController.textFields.firstObject;
  373. UIAlertAction *okAction = alertController.actions.lastObject;
  374. okAction.enabled = fileName.text.length > 0;
  375. }
  376. }
  377. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  378. [textField selectAll:textField];
  379. }
  380. #pragma --------------------------------------------------------------------------------------------
  381. #pragma mark ===== Graphic Window =====
  382. #pragma --------------------------------------------------------------------------------------------
  383. - (void)createRefreshControl
  384. {
  385. _refreshControl = [UIRefreshControl new];
  386. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  387. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  388. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  389. [self setRefreshControl:_refreshControl];
  390. }
  391. - (void)deleteRefreshControl
  392. {
  393. [_refreshControl endRefreshing];
  394. self.refreshControl = nil;
  395. }
  396. - (void)refreshControlTarget
  397. {
  398. [self readFolder:_serverUrl];
  399. // Actuate `Peek` feedback (weak boom)
  400. AudioServicesPlaySystemSound(1519);
  401. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  402. }
  403. - (void)setTitle
  404. {
  405. // Color text self.navigationItem.title
  406. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  407. if (_isSelectedMode) {
  408. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  409. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  410. self.navigationItem.titleView = nil;
  411. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  412. } else {
  413. // we are in home : LOGO BRAND
  414. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  415. self.navigationItem.title = nil;
  416. if ([app.reachability isReachable] == NO)
  417. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  418. else
  419. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  420. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  421. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  422. [singleTap setNumberOfTapsRequired:1];
  423. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  424. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  425. } else {
  426. self.navigationItem.title = _titleMain;
  427. }
  428. }
  429. }
  430. - (void)setUINavigationBarDefault
  431. {
  432. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  433. UIBarButtonItem *buttonMore, *buttonNotification;
  434. // =
  435. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  436. buttonMore.enabled = true;
  437. // <
  438. self.navigationController.navigationBar.hidden = NO;
  439. // Notification
  440. if ([app.listOfNotifications count] > 0) {
  441. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  442. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  443. buttonNotification.enabled = true;
  444. }
  445. if (buttonNotification)
  446. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  447. else
  448. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  449. self.navigationItem.leftBarButtonItem = nil;
  450. }
  451. - (void)setUINavigationBarSelected
  452. {
  453. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  454. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  455. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  456. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  457. self.navigationItem.leftBarButtonItem = leftButton;
  458. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  459. }
  460. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  461. {
  462. [self closeAllMenu];
  463. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  464. }];
  465. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  466. }
  467. - (void)cancelSelect
  468. {
  469. [self tableViewSelect:NO];
  470. [app.reSelectMenu close];
  471. }
  472. - (void)closeAllMenu
  473. {
  474. // close Menu
  475. [app.reSelectMenu close];
  476. [app.reMainMenu close];
  477. // Close Menu Logo
  478. [CCMenuAccount dismissMenu];
  479. }
  480. #pragma --------------------------------------------------------------------------------------------
  481. #pragma mark ===== Document Picker =====
  482. #pragma --------------------------------------------------------------------------------------------
  483. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  484. {
  485. NSLog(@"Cancelled");
  486. }
  487. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  488. {
  489. NSLog(@"Cancelled");
  490. }
  491. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  492. {
  493. documentPicker.delegate = self;
  494. [self presentViewController:documentPicker animated:YES completion:nil];
  495. }
  496. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  497. {
  498. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  499. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  500. __block NSError *error;
  501. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  502. NSString *fileName = [url lastPathComponent];
  503. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  504. NSData *data = [NSData dataWithContentsOfURL:newURL];
  505. if (data && error == nil) {
  506. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  507. // Upload File
  508. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  509. } else {
  510. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  511. }
  512. } else {
  513. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  514. }
  515. }];
  516. }
  517. }
  518. - (void)openImportDocumentPicker
  519. {
  520. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  521. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  522. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  523. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  524. documentProviderMenu.delegate = self;
  525. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  526. }
  527. #pragma --------------------------------------------------------------------------------------------
  528. #pragma mark ===== Assets Picker =====
  529. #pragma --------------------------------------------------------------------------------------------
  530. -(void)dismissFormUploadAssets
  531. {
  532. [self reloadDatasource];
  533. }
  534. - (void)openAssetsPickerController
  535. {
  536. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  537. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  538. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  539. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  540. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  541. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  542. dispatch_async(dispatch_get_main_queue(), ^{
  543. // init picker
  544. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  545. // set delegate
  546. picker.delegate = self;
  547. // to show selection order
  548. //picker.showsSelectionIndex = YES;
  549. // to present picker as a form sheet in iPad
  550. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  551. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  552. // present picker
  553. [self presentViewController:picker animated:YES completion:nil];
  554. });
  555. }];
  556. }
  557. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  558. {
  559. [picker dismissViewControllerAnimated:YES completion:^{
  560. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session delegate:self];
  561. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  562. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  563. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  564. [self presentViewController:navigationController animated:YES completion:nil];
  565. }];
  566. }
  567. #pragma --------------------------------------------------------------------------------------------
  568. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  569. #pragma --------------------------------------------------------------------------------------------
  570. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  571. {
  572. // evitiamo il rimando della eventuale photo e/o video
  573. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  574. if (tableAccount.autoUpload) {
  575. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  576. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  577. }
  578. }
  579. /*
  580. #pragma --------------------------------------------------------------------------------------------
  581. #pragma mark ===== UnZipFile =====
  582. #pragma --------------------------------------------------------------------------------------------
  583. - (void)unZipFile:(NSString *)fileID
  584. {
  585. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  586. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  587. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  588. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  589. dispatch_async(dispatch_get_main_queue(), ^{
  590. float progress = (float) entryNumber / (float)total;
  591. [_hudDeterminate progress:progress];
  592. });
  593. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  594. dispatch_async(dispatch_get_main_queue(), ^{
  595. [_hudDeterminate hideHud];
  596. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  597. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  598. });
  599. }];
  600. });
  601. }
  602. */
  603. #pragma --------------------------------------------------------------------------------------------
  604. #pragma mark ===== Create New (OpenModel) =====
  605. #pragma --------------------------------------------------------------------------------------------
  606. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  607. {
  608. UIViewController *viewController;
  609. NSString *fileName, *uuid, *fileID, *serverUrl;
  610. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  611. [self.tableView deselectRowAtIndexPath:index animated:NO];
  612. if (isnew) {
  613. fileName = nil;
  614. uuid = [CCUtility getUUID];
  615. fileID = nil;
  616. serverUrl = _serverUrl;
  617. } else {
  618. fileName = _metadata.fileName;
  619. uuid = _metadata.uuid;
  620. fileID = _metadata.fileID;
  621. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  622. }
  623. if ([tipo isEqualToString:@"cartadicredito"])
  624. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  625. if ([tipo isEqualToString:@"bancomat"])
  626. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  627. if ([tipo isEqualToString:@"contocorrente"])
  628. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  629. if ([tipo isEqualToString:@"accountweb"])
  630. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  631. if ([tipo isEqualToString:@"patenteguida"])
  632. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  633. if ([tipo isEqualToString:@"cartaidentita"])
  634. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  635. if ([tipo isEqualToString:@"passaporto"])
  636. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  637. if ([tipo isEqualToString:@"note"]) {
  638. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  639. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  640. [self presentViewController:navigationController animated:YES completion:nil];
  641. } else {
  642. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  643. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  644. [self presentViewController:navigationController animated:YES completion:nil];
  645. }
  646. }
  647. // New folder or new photo or video
  648. - (void)returnCreate:(NSInteger)type
  649. {
  650. switch (type) {
  651. /* PLAIN */
  652. case k_returnCreateFolderPlain: {
  653. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  654. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  655. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  656. }];
  657. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  658. NSLog(@"Cancel action");
  659. }];
  660. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  661. UITextField *fileName = alertController.textFields.firstObject;
  662. [self createFolder:fileName.text autoUploadDirectory:NO];
  663. }];
  664. okAction.enabled = NO;
  665. [alertController addAction:cancelAction];
  666. [alertController addAction:okAction];
  667. [self presentViewController:alertController animated:YES completion:nil];
  668. }
  669. break;
  670. case k_returnCreateFotoVideoPlain: {
  671. _isPickerCriptate = false;
  672. [self openAssetsPickerController];
  673. }
  674. break;
  675. case k_returnCreateFilePlain: {
  676. _isPickerCriptate = false;
  677. [self openImportDocumentPicker];
  678. }
  679. break;
  680. /* ENCRYPTED */
  681. case k_returnCreateFolderEncrypted: {
  682. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  683. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  684. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  685. }];
  686. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  687. NSLog(@"Cancel action");
  688. }];
  689. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  690. UITextField *fileName = alertController.textFields.firstObject;
  691. [self createFolderEncrypted:fileName.text];
  692. }];
  693. okAction.enabled = NO;
  694. [alertController addAction:cancelAction];
  695. [alertController addAction:okAction];
  696. [self presentViewController:alertController animated:YES completion:nil];
  697. }
  698. break;
  699. case k_returnCreateFotoVideoEncrypted: {
  700. _isPickerCriptate = true;
  701. [self openAssetsPickerController];
  702. }
  703. break;
  704. case k_returnCreateFileEncrypted: {
  705. _isPickerCriptate = true;
  706. [self openImportDocumentPicker];
  707. }
  708. break;
  709. /* UTILITY */
  710. case k_returnNote:
  711. [self openModel:@"note" isNew:true];
  712. break;
  713. case k_returnAccountWeb:
  714. [self openModel:@"accountweb" isNew:true];
  715. break;
  716. /* BANK */
  717. case k_returnCartaDiCredito:
  718. [self openModel:@"cartadicredito" isNew:true];
  719. break;
  720. case k_returnBancomat:
  721. [self openModel:@"bancomat" isNew:true];
  722. break;
  723. case k_returnContoCorrente:
  724. [self openModel:@"contocorrente" isNew:true];
  725. break;
  726. /* DOCUMENT */
  727. case k_returnPatenteGuida:
  728. [self openModel:@"patenteguida" isNew:true];
  729. break;
  730. case k_returnCartaIdentita:
  731. [self openModel:@"cartaidentita" isNew:true];
  732. break;
  733. case k_returnPassaporto:
  734. [self openModel:@"passaporto" isNew:true];
  735. break;
  736. }
  737. }
  738. #pragma --------------------------------------------------------------------------------------------
  739. #pragma mark ===== Save selected File =====
  740. #pragma --------------------------------------------------------------------------------------------
  741. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  742. {
  743. if (error)
  744. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  745. else
  746. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  747. }
  748. - (void)saveSelectedFiles
  749. {
  750. NSLog(@"[LOG] Start download selected files ...");
  751. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  752. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  753. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  754. for (tableMetadata *metadata in metadatas) {
  755. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  756. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  757. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  758. }
  759. }
  760. [_hud hideHud];
  761. });
  762. [self tableViewSelect:NO];
  763. }
  764. #pragma --------------------------------------------------------------------------------------------
  765. #pragma mark ===== Change Password =====
  766. #pragma --------------------------------------------------------------------------------------------
  767. - (void) loginSuccess:(NSInteger)loginType
  768. {
  769. [self readFolder:_serverUrl];
  770. }
  771. - (void)changePasswordAccount
  772. {
  773. // Brand
  774. if ([NCBrandOptions sharedInstance].use_login_web) {
  775. _loginWeb = [CCLoginWeb new];
  776. _loginWeb.delegate = self;
  777. _loginWeb.loginType = loginModifyPasswordUser;
  778. dispatch_async(dispatch_get_main_queue(), ^ {
  779. [_loginWeb presentModalWithDefaultTheme:self];
  780. });
  781. } else {
  782. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  783. _loginVC.delegate = self;
  784. _loginVC.loginType = loginModifyPasswordUser;
  785. [self presentViewController:_loginVC animated:YES completion:nil];
  786. }
  787. }
  788. #pragma mark -
  789. #pragma --------------------------------------------------------------------------------------------
  790. #pragma mark ===== Peek & Pop =====
  791. #pragma --------------------------------------------------------------------------------------------
  792. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  793. {
  794. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  795. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  796. if (metadata.thumbnailExists && !metadata.cryptated) {
  797. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  798. if (cell) {
  799. previewingContext.sourceRect = cell.frame;
  800. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  801. vc.delegate = self;
  802. vc.metadata = metadata;
  803. return vc;
  804. }
  805. }
  806. return nil;
  807. }
  808. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  809. {
  810. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  811. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  812. }
  813. #pragma mark -
  814. #pragma --------------------------------------------------------------------------------------------
  815. #pragma mark ==== External Sites ====
  816. #pragma --------------------------------------------------------------------------------------------
  817. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  818. {
  819. [[NCManageDatabase sharedInstance] deleteExternalSites];
  820. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  821. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  822. }
  823. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  824. {
  825. NSLog(@"[LOG] No External Sites found");
  826. }
  827. #pragma --------------------------------------------------------------------------------------------
  828. #pragma mark ==== Activity ====
  829. #pragma --------------------------------------------------------------------------------------------
  830. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  831. {
  832. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  833. // Reload Activity Data Source
  834. [app.activeActivity reloadDatasource];
  835. }
  836. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  837. {
  838. NSLog(@"[LOG] No Activity found");
  839. }
  840. #pragma --------------------------------------------------------------------------------------------
  841. #pragma mark ==== Notification ====
  842. #pragma --------------------------------------------------------------------------------------------
  843. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  844. {
  845. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  846. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  847. // Order by date
  848. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  849. OCNotifications *notification1 = obj1, *notification2 = obj2;
  850. return [notification2.date compare: notification1.date];
  851. }];
  852. // verify if listOfNotifications is changed
  853. NSString *old = @"", *new = @"";
  854. for (OCNotifications *notification in listOfNotifications)
  855. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  856. for (OCNotifications *notification in appDelegate.listOfNotifications)
  857. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  858. if (![new isEqualToString:old]) {
  859. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  860. // reload Notification view
  861. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  862. }
  863. // Update NavigationBar
  864. if (!_isSelectedMode) {
  865. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  866. }
  867. });
  868. }
  869. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  870. {
  871. // Update NavigationBar
  872. if (!_isSelectedMode)
  873. [self setUINavigationBarDefault];
  874. }
  875. - (void)viewNotification
  876. {
  877. if ([app.listOfNotifications count] > 0) {
  878. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  879. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  880. [self presentViewController:notificationVC animated:YES completion:nil];
  881. }
  882. }
  883. #pragma --------------------------------------------------------------------------------------------
  884. #pragma mark ==== User Profile ====
  885. #pragma --------------------------------------------------------------------------------------------
  886. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  887. {
  888. if (errorCode == 401)
  889. [self changePasswordAccount];
  890. }
  891. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  892. {
  893. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  894. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  895. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  896. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  897. if (avatar)
  898. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  899. else
  900. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  901. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  902. });
  903. }
  904. #pragma --------------------------------------------------------------------------------------------
  905. #pragma mark ==== Capabilities ====
  906. #pragma --------------------------------------------------------------------------------------------
  907. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  908. {
  909. // Change Theming color
  910. [app settingThemingColorBrand];
  911. if (errorCode == 401)
  912. [self changePasswordAccount];
  913. }
  914. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  915. {
  916. // Update capabilities db
  917. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  918. // ------ THEMING -----------------------------------------------------------------------
  919. // Download Theming Background & Change Theming color
  920. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  921. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  922. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  923. if (themingBackground)
  924. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  925. else
  926. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  927. }
  928. dispatch_async(dispatch_get_main_queue(), ^{
  929. [app settingThemingColorBrand];
  930. });
  931. });
  932. // ------ SEARCH ------------------------------------------------------------------------
  933. // Search bar if change version
  934. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  935. [self cancelSearchBar];
  936. }
  937. // ------ GET SERVICE SERVER ------------------------------------------------------------
  938. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  939. // Read External Sites
  940. if (capabilities.isExternalSitesServerEnabled) {
  941. metadataNet.action = actionGetExternalSitesServer;
  942. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  943. }
  944. // Read Share
  945. if (capabilities.isFilesSharingAPIEnabled) {
  946. [app.sharesID removeAllObjects];
  947. metadataNet.action = actionReadShareServer;
  948. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  949. }
  950. // Read Notification
  951. metadataNet.action = actionGetNotificationServer;
  952. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  953. // Read User Profile
  954. metadataNet.action = actionGetUserProfile;
  955. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  956. // Read Activity
  957. metadataNet.action = actionGetActivityServer;
  958. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  959. }
  960. #pragma mark -
  961. #pragma --------------------------------------------------------------------------------------------
  962. #pragma mark ==== Request Server Information ====
  963. #pragma --------------------------------------------------------------------------------------------
  964. - (void)requestServerCapabilities
  965. {
  966. // test
  967. if (app.activeAccount.length == 0)
  968. return;
  969. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  970. metadataNet.action = actionGetCapabilities;
  971. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  972. }
  973. #pragma mark -
  974. #pragma --------------------------------------------------------------------------------------------
  975. #pragma mark ==== Middleware Ping ====
  976. #pragma --------------------------------------------------------------------------------------------
  977. - (void)middlewarePing
  978. {
  979. // test
  980. if (app.activeAccount.length == 0)
  981. return;
  982. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  983. metadataNet.action = actionMiddlewarePing;
  984. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  985. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  986. }
  987. #pragma mark -
  988. #pragma --------------------------------------------------------------------------------------------
  989. #pragma mark ==== Download Thumbnail Delegate ====
  990. #pragma --------------------------------------------------------------------------------------------
  991. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  992. {
  993. __block CCCellMain *cell;
  994. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  995. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  996. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  997. cell.file.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  998. if (cell.file.image == nil) {
  999. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1000. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  1001. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  1002. });
  1003. }
  1004. }
  1005. }
  1006. #pragma --------------------------------------------------------------------------------------------
  1007. #pragma mark ==== Download ====
  1008. #pragma --------------------------------------------------------------------------------------------
  1009. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1010. {
  1011. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1012. // File do not exists on server, remove in local
  1013. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1014. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1015. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1016. if (metadata.directory && serverUrl) {
  1017. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  1018. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  1019. }
  1020. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1021. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1022. }
  1023. if ([selector isEqualToString:selectorLoadViewImage]) {
  1024. dispatch_async(dispatch_get_main_queue(), ^{
  1025. // Updating Detail
  1026. if (app.activeDetail)
  1027. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1028. // Updating Photos
  1029. if (app.activePhotos)
  1030. [app.activePhotos downloadFileFailure:errorCode];
  1031. });
  1032. } else {
  1033. if (errorCode != kCFURLErrorCancelled)
  1034. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1035. }
  1036. [self reloadDatasource:serverUrl];
  1037. }
  1038. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1039. {
  1040. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1041. if (metadata == nil)
  1042. return;
  1043. // Download
  1044. if ([selector isEqualToString:selectorDownloadFile]) {
  1045. [self reloadDatasource:serverUrl];
  1046. }
  1047. // Synchronized
  1048. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1049. [self reloadDatasource:serverUrl];
  1050. }
  1051. // add Favorite
  1052. if ([selector isEqualToString:selectorAddFavorite]) {
  1053. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1054. }
  1055. // encrypted file
  1056. if ([selector isEqualToString:selectorEncryptFile]) {
  1057. [self encryptedFile:metadata];
  1058. }
  1059. // decrypted file
  1060. if ([selector isEqualToString:selectorDecryptFile]) {
  1061. [self decryptedFile:metadata];
  1062. }
  1063. // open View File
  1064. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1065. [self reloadDatasource:serverUrl];
  1066. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1067. selector = selectorOpenIn;
  1068. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1069. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1070. selector = selectorOpenIn;
  1071. } else {
  1072. _metadata = metadata;
  1073. if ([self shouldPerformSegue])
  1074. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1075. }
  1076. }
  1077. // addLocal
  1078. if ([selector isEqualToString:selectorAddLocal]) {
  1079. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1080. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1081. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1082. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1083. [self reloadDatasource:serverUrl];
  1084. }
  1085. // Open with...
  1086. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1087. [self reloadDatasource:serverUrl];
  1088. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1089. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1090. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1091. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1092. _docController.delegate = self;
  1093. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1094. }
  1095. // Save to Photo Album
  1096. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1097. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1098. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1099. // evitiamo il rimando photo
  1100. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1101. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1102. if (image)
  1103. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1104. else
  1105. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1106. }
  1107. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1108. // we avoid the cross-reference video
  1109. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1110. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1111. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1112. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1113. } else {
  1114. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1115. }
  1116. }
  1117. [self reloadDatasource:serverUrl];
  1118. }
  1119. // Copy File
  1120. if ([selector isEqualToString:selectorLoadCopy]) {
  1121. [self reloadDatasource:serverUrl];
  1122. [self copyFileToPasteboard:metadata];
  1123. }
  1124. // download and view a template
  1125. if ([selector isEqualToString:selectorLoadModelView]) {
  1126. // se è un template aggiorniamo anche nel FileSystem
  1127. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1128. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1129. }
  1130. [self openModel:metadata.model isNew:false];
  1131. [self reloadDatasource:serverUrl];
  1132. }
  1133. //download file plist
  1134. if ([selector isEqualToString:selectorLoadPlist]) {
  1135. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1136. long countSelectorLoadPlist = 0;
  1137. for (NSOperation *operation in [app.netQueue operations]) {
  1138. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1139. countSelectorLoadPlist++;
  1140. }
  1141. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1142. dispatch_async(dispatch_get_main_queue(), ^{
  1143. [self reloadDatasource:serverUrl];
  1144. });
  1145. }
  1146. });
  1147. }
  1148. //selectorLoadViewImage
  1149. if ([selector isEqualToString:selectorLoadViewImage]) {
  1150. // Detail
  1151. if (app.activeDetail)
  1152. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1153. // Photos
  1154. if (app.activePhotos)
  1155. [app.activePhotos downloadFileSuccess:metadata];
  1156. [self reloadDatasource:serverUrl];
  1157. }
  1158. // if exists postselector call self with selectorPost
  1159. if ([selectorPost length] > 0)
  1160. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1161. }
  1162. - (void)downloadSelectedFilesFolders
  1163. {
  1164. NSLog(@"[LOG] Start download selected ...");
  1165. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1166. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1167. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1168. for (tableMetadata *metadata in selectedMetadatas) {
  1169. if ([metadata.type isEqualToString: k_metadataType_file]) {
  1170. if (metadata.directory) {
  1171. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1172. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1173. [[CCSynchronize sharedSynchronize] synchronizedFolder:serverUrl selector:selectorReadFolderWithDownload];
  1174. } else {
  1175. [[CCSynchronize sharedSynchronize] synchronizedFile:metadata selector:selectorReadFileWithDownload];
  1176. }
  1177. }
  1178. }
  1179. [_hud hideHud];
  1180. });
  1181. [self tableViewSelect:NO];
  1182. }
  1183. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1184. {
  1185. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1186. for (tableMetadata *metadata in metadatas) {
  1187. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1188. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1189. metadataNet.action = actionDownloadFile;
  1190. metadataNet.downloadData = NO;
  1191. metadataNet.downloadPlist = YES;
  1192. metadataNet.fileID = metadata.fileID;
  1193. metadataNet.selector = selectorLoadPlist;
  1194. metadataNet.serverUrl = serverUrl;
  1195. metadataNet.session = k_download_session_foreground;
  1196. metadataNet.taskStatus = k_taskStatusResume;
  1197. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1198. //[[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selectorLoadPlist selectorPost:nil session:k_download_session_foreground taskStatus:k_taskStatusResume delegate:self];
  1199. }
  1200. }
  1201. }
  1202. #pragma --------------------------------------------------------------------------------------------
  1203. #pragma mark ===== Upload new Photos/Videos =====
  1204. #pragma --------------------------------------------------------------------------------------------
  1205. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1206. {
  1207. // Auto Upload
  1208. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1209. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1210. // ONLY BACKGROUND
  1211. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1212. } else {
  1213. // ONLY FOREFROUND
  1214. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1215. }
  1216. }
  1217. // Read File test do not exists
  1218. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1219. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1220. // reUpload
  1221. if (metadata)
  1222. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1223. }
  1224. // Print error
  1225. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1226. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1227. }
  1228. [self reloadDatasource:serverUrl];
  1229. }
  1230. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1231. {
  1232. // Auto Upload
  1233. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1234. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1235. // ONLY BACKGROUND
  1236. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1237. } else {
  1238. // ONLY FOREFROUND
  1239. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1240. }
  1241. }
  1242. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1243. [self readFolder:serverUrl];
  1244. } else {
  1245. [self reloadDatasource:serverUrl];
  1246. }
  1247. }
  1248. //
  1249. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1250. //
  1251. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1252. {
  1253. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1254. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1255. });
  1256. }
  1257. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1258. {
  1259. NSArray *assets = [arguments objectAtIndex:0];
  1260. NSString *serverUrl = [arguments objectAtIndex:1];
  1261. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1262. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1263. NSString *session = [arguments objectAtIndex:4];
  1264. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1265. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1266. // Create the folder for Photos & if request the subfolders
  1267. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1268. return;
  1269. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1270. for (PHAsset *asset in assets) {
  1271. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1272. NSDate *assetDate = asset.creationDate;
  1273. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1274. // Create serverUrl if use sub folder
  1275. if (useSubFolder) {
  1276. [formatter setDateFormat:@"yyyy"];
  1277. NSString *yearString = [formatter stringFromDate:assetDate];
  1278. [formatter setDateFormat:@"MM"];
  1279. NSString *monthString = [formatter stringFromDate:assetDate];
  1280. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1281. }
  1282. // Check if is in upload
  1283. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1284. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1285. if ([isRecordInSessions count] > 0) {
  1286. // next upload
  1287. continue;
  1288. } else {
  1289. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1290. if (cryptated) {
  1291. metadataNet.action = actionUploadAsset;
  1292. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1293. metadataNet.cryptated = cryptated;
  1294. metadataNet.fileName = fileName;
  1295. metadataNet.session = session;
  1296. metadataNet.selector = selectorUploadFile;
  1297. metadataNet.selectorPost = nil;
  1298. metadataNet.serverUrl = serverUrl;
  1299. metadataNet.taskStatus = k_taskStatusResume;
  1300. } else {
  1301. metadataNet.action = actionReadFile;
  1302. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1303. metadataNet.cryptated = cryptated;
  1304. metadataNet.fileName = fileName;
  1305. metadataNet.session = session;
  1306. metadataNet.selector = selectorReadFileUploadFile;
  1307. metadataNet.serverUrl = serverUrl;
  1308. }
  1309. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1310. }
  1311. }
  1312. }
  1313. #pragma --------------------------------------------------------------------------------------------
  1314. #pragma mark ==== Read File ====
  1315. #pragma --------------------------------------------------------------------------------------------
  1316. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1317. {
  1318. // Read Folder
  1319. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1320. //[self readFolderWithForced:NO serverUrl:metadataNet.serverUrl];
  1321. }
  1322. // UploadFile
  1323. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1324. // File not exists
  1325. if (errorCode == 404) {
  1326. metadataNet.action = actionUploadAsset;
  1327. metadataNet.errorCode = 0;
  1328. metadataNet.selector = selectorUploadFile;
  1329. metadataNet.selectorPost = nil;
  1330. metadataNet.taskStatus = k_taskStatusResume;
  1331. if ([metadataNet.session containsString:@"wwan"])
  1332. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1333. else
  1334. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1335. } else {
  1336. // error ho many retry befor notification and go to on next asses
  1337. if (metadataNet.errorRetry < 3) {
  1338. // Retry read file
  1339. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1340. } else {
  1341. // STOP check file, view message error
  1342. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1343. }
  1344. }
  1345. }
  1346. }
  1347. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1348. {
  1349. // Read Folder
  1350. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1351. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1352. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1353. [self readFolder:metadataNet.serverUrl];
  1354. }
  1355. }
  1356. // UploadFile
  1357. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1358. metadataNet.action = actionUploadAsset;
  1359. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1360. metadataNet.selector = selectorUploadFile;
  1361. metadataNet.selectorPost = nil;
  1362. metadataNet.taskStatus = k_taskStatusResume;
  1363. if ([metadataNet.session containsString:@"wwan"])
  1364. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1365. else
  1366. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1367. }
  1368. }
  1369. - (void)readFileReloadFolder
  1370. {
  1371. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1372. return;
  1373. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1374. metadataNet.action = actionReadFile;
  1375. metadataNet.priority = NSOperationQueuePriorityHigh;
  1376. metadataNet.selector = selectorReadFileReloadFolder;
  1377. metadataNet.serverUrl = _serverUrl;
  1378. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1379. }
  1380. #pragma --------------------------------------------------------------------------------------------
  1381. #pragma mark ==== Read Folder ====
  1382. #pragma --------------------------------------------------------------------------------------------
  1383. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1384. {
  1385. // verify active user
  1386. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1387. _loadingFolder = NO;
  1388. [self tableViewReloadData];
  1389. [_refreshControl endRefreshing];
  1390. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1391. if (message && [record.account isEqualToString:metadataNet.account])
  1392. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1393. [self reloadDatasource:metadataNet.serverUrl];
  1394. if (errorCode == 401)
  1395. [self changePasswordAccount];
  1396. }
  1397. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1398. {
  1399. // verify active user
  1400. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1401. if (![record.account isEqualToString:metadataNet.account])
  1402. return;
  1403. // save father e update permission
  1404. if(!_isSearchMode && metadataFolder)
  1405. _fatherPermission = metadataFolder.permissions;
  1406. NSArray *recordsInSessions;
  1407. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1408. if (_isSearchMode) {
  1409. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1410. } else {
  1411. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1412. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1413. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1414. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1415. }
  1416. for (tableMetadata *metadata in metadatas) {
  1417. // type of file
  1418. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1419. // if crypto do not insert
  1420. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1421. // verify if the record encrypted has plist + crypto
  1422. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1423. BOOL isCryptoComplete = NO;
  1424. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1425. for (tableMetadata *completeMetadata in metadatas) {
  1426. if (completeMetadata.cryptated == NO) continue;
  1427. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1428. isCryptoComplete = YES;
  1429. break;
  1430. }
  1431. }
  1432. if (isCryptoComplete == NO) continue;
  1433. }
  1434. // verify if the record is in download/upload progress
  1435. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1436. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1437. // is in Download or Upload
  1438. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1439. continue;
  1440. }
  1441. }
  1442. // Insert in Array
  1443. [metadatasToInsertInDB addObject:metadata];
  1444. }
  1445. // insert in Database
  1446. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB activeUrl:app.activeUrl serverUrl:metadataNet.serverUrl];
  1447. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1448. // read plist
  1449. if (!_isSearchMode)
  1450. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1451. // File is changed ??
  1452. if (!_isSearchMode && metadatasToInsertInDB)
  1453. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1454. });
  1455. // Search Mode
  1456. if (_isSearchMode) {
  1457. // Fix managed -> Unmanaged _searchResultMetadatas
  1458. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1459. [self reloadDatasource:metadataNet.serverUrl];
  1460. }
  1461. // this is the same directory
  1462. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1463. // reload
  1464. [self reloadDatasource:metadataNet.serverUrl];
  1465. // stoprefresh
  1466. [_refreshControl endRefreshing];
  1467. // Enable change user
  1468. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1469. _loadingFolder = NO;
  1470. [self tableViewReloadData];
  1471. }
  1472. }
  1473. - (void)readFolder:(NSString *)serverUrl
  1474. {
  1475. // init control
  1476. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1477. [_refreshControl endRefreshing];
  1478. return;
  1479. }
  1480. // Search Mode
  1481. if (_isSearchMode) {
  1482. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1483. _searchFileName = @""; // forced reload searchg
  1484. [self updateSearchResultsForSearchController:self.searchController];
  1485. return;
  1486. }
  1487. _loadingFolder = YES;
  1488. [self tableViewReloadData];
  1489. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1490. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1491. metadataNet.action = actionReadFolder;
  1492. metadataNet.date = [NSDate date];
  1493. metadataNet.directoryID = directory.directoryID;
  1494. metadataNet.priority = NSOperationQueuePriorityHigh;
  1495. metadataNet.selector = selectorReadFolder;
  1496. metadataNet.serverUrl = serverUrl;
  1497. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1498. }
  1499. #pragma mark -
  1500. #pragma --------------------------------------------------------------------------------------------
  1501. #pragma mark ===== Search =====
  1502. #pragma --------------------------------------------------------------------------------------------
  1503. -(void)searchStartTimer
  1504. {
  1505. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1506. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:_depth date:nil selector:selectorSearch delegate:self];
  1507. _noFilesSearchTitle = @"";
  1508. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1509. [self.tableView reloadEmptyDataSet];
  1510. }
  1511. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1512. {
  1513. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  1514. _isSearchMode = YES;
  1515. [self deleteRefreshControl];
  1516. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1517. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1518. _searchFileName = fileName;
  1519. // First : filter
  1520. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1521. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1522. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1523. [_searchResultMetadatas removeAllObjects];
  1524. for (tableMetadata *record in records)
  1525. [_searchResultMetadatas addObject:record];
  1526. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1527. metadataNet.account = app.activeAccount;
  1528. metadataNet.directoryID = directoryID;
  1529. metadataNet.selector = selectorSearch;
  1530. metadataNet.serverUrl = _serverUrl;
  1531. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1532. // Version >= 12
  1533. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1534. [_timerWaitInput invalidate];
  1535. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1536. }
  1537. }
  1538. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1539. [self reloadDatasource];
  1540. }
  1541. }
  1542. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1543. {
  1544. [self cancelSearchBar];
  1545. [self readFolder:_serverUrl];
  1546. }
  1547. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1548. {
  1549. _searchFileName = @"";
  1550. if (message)
  1551. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1552. }
  1553. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1554. {
  1555. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1556. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1557. }
  1558. - (void)cancelSearchBar
  1559. {
  1560. if (self.searchController.active) {
  1561. [self.searchController setActive:NO];
  1562. [self createRefreshControl];
  1563. _isSearchMode = NO;
  1564. _searchFileName = @"";
  1565. _dateReadDataSource = nil;
  1566. _searchResultMetadatas = [NSMutableArray new];
  1567. [self reloadDatasource];
  1568. }
  1569. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  1570. }
  1571. #pragma mark -
  1572. #pragma --------------------------------------------------------------------------------------------
  1573. #pragma mark ===== Delete File or Folder =====
  1574. #pragma --------------------------------------------------------------------------------------------
  1575. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1576. {
  1577. [self deleteFileOrFolderSuccess:metadataNet];
  1578. }
  1579. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1580. {
  1581. [_queueSelector removeObject:metadataNet.selector];
  1582. if ([_queueSelector count] == 0) {
  1583. [_hud hideHud];
  1584. // next
  1585. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1586. if ([_selectedFileIDsMetadatas count] > 0) {
  1587. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1588. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1589. } else {
  1590. // End Select Table View
  1591. [self tableViewSelect:NO];
  1592. // Reload
  1593. if (_isSearchMode)
  1594. [self readFolder:metadataNet.serverUrl];
  1595. else
  1596. [self reloadDatasource:metadataNet.serverUrl];
  1597. }
  1598. }
  1599. }
  1600. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1601. {
  1602. if (metadata.cryptated) {
  1603. [_queueSelector addObject:selectorDeleteCrypto];
  1604. [_queueSelector addObject:selectorDeletePlist];
  1605. } else {
  1606. [_queueSelector addObject:selectorDelete];
  1607. }
  1608. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1609. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1610. }
  1611. - (void)deleteFile
  1612. {
  1613. [_queueSelector removeAllObjects];
  1614. if ([_selectedFileIDsMetadatas count] > 0) {
  1615. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1616. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1617. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1618. } else {
  1619. _numSelectedFileIDsMetadatas = 1;
  1620. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1621. }
  1622. }
  1623. #pragma --------------------------------------------------------------------------------------------
  1624. #pragma mark ===== Rename / Move =====
  1625. #pragma --------------------------------------------------------------------------------------------
  1626. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1627. {
  1628. [self readFolder:metadataNet.serverUrl];
  1629. }
  1630. - (void)renameFile:(NSArray *)arguments
  1631. {
  1632. tableMetadata* metadata = [arguments objectAtIndex:0];
  1633. NSString *fileName = [arguments objectAtIndex:1];
  1634. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1635. }
  1636. - (void)renameNote:(NSArray *)arguments
  1637. {
  1638. tableMetadata* metadata = [arguments objectAtIndex:0];
  1639. NSString *fileName = [arguments objectAtIndex:1];
  1640. CCTemplates *templates = [[CCTemplates alloc] init];
  1641. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1642. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1643. if (fileNameModel) {
  1644. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1645. metadataNet.action = actionUploadTemplate;
  1646. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1647. metadataNet.fileNamePrint = fileName;
  1648. metadataNet.etag = metadata.etag;
  1649. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1650. metadataNet.session = k_upload_session_foreground;
  1651. metadataNet.taskStatus = k_taskStatusResume;
  1652. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1653. }
  1654. }
  1655. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1656. {
  1657. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1658. [_hud hideHud];
  1659. if (message)
  1660. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1661. // End Select Table View
  1662. [self tableViewSelect:NO];
  1663. // reload Datasource
  1664. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1665. [self readFolder:metadataNet.serverUrl];
  1666. else
  1667. [self reloadDatasource];
  1668. }
  1669. }
  1670. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1671. {
  1672. [_queueSelector removeObject:metadataNet.selector];
  1673. if ([_queueSelector count] == 0) {
  1674. [_hud hideHud];
  1675. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1676. NSString *directoryID = metadataNet.directoryID;
  1677. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1678. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1679. // FILE -> Metadata
  1680. if (metadataNet.directory == NO) {
  1681. // move metadata
  1682. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1683. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1684. }
  1685. // DIRECTORY -> Directory - CCMetadata
  1686. if (metadataNet.directory == YES) {
  1687. // delete all dir / subdir
  1688. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1689. // move metadata
  1690. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1691. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1692. // Add new directory
  1693. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1694. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1695. }
  1696. // next
  1697. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1698. if ([_selectedFileIDsMetadatas count] > 0) {
  1699. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1700. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1701. } else {
  1702. // End Select Table View
  1703. [self tableViewSelect:NO];
  1704. // reload Datasource
  1705. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1706. [self readFolder:metadataNet.serverUrl];
  1707. else
  1708. [self reloadDatasource];
  1709. }
  1710. }
  1711. }
  1712. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1713. {
  1714. tableMetadata *metadata = [arguments objectAtIndex:0];
  1715. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1716. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1717. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1718. // Plain
  1719. if (metadata.cryptated == NO) {
  1720. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1721. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1722. if(!error) {
  1723. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1724. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1725. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1726. }];
  1727. [alert addAction:ok];
  1728. [self presentViewController:alert animated:YES completion:nil];
  1729. });
  1730. // End Select Table View
  1731. [self tableViewSelect:NO];
  1732. // reload Datasource
  1733. [self readFileReloadFolder];
  1734. return;
  1735. }
  1736. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1737. metadataNet.action = actionMoveFileOrFolder;
  1738. metadataNet.directory = metadata.directory;
  1739. metadataNet.fileID = metadata.fileID;
  1740. metadataNet.directoryID = metadata.directoryID;
  1741. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1742. metadataNet.fileName = metadata.fileName;
  1743. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1744. metadataNet.fileNameTo = metadata.fileName;
  1745. metadataNet.etag = metadata.etag;
  1746. metadataNet.selector = selectorMove;
  1747. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1748. metadataNet.serverUrlTo = serverUrlTo;
  1749. [_queueSelector addObject:metadataNet.selector];
  1750. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1751. }
  1752. // cyptated
  1753. if (metadata.cryptated == YES) {
  1754. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1755. metadataNet.action = actionMoveFileOrFolder;
  1756. metadataNet.directory = metadata.directory;
  1757. metadataNet.fileID = metadata.fileID;
  1758. metadataNet.directoryID = metadata.directoryID;
  1759. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1760. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1761. metadataNet.etag = metadata.etag;
  1762. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1763. metadataNet.serverUrlTo = serverUrlTo;
  1764. // data
  1765. metadataNet.fileName = metadata.fileNameData;
  1766. metadataNet.fileNameTo = metadata.fileNameData;
  1767. metadataNet.selector = selectorMoveCrypto;
  1768. [_queueSelector addObject:metadataNet.selector];
  1769. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1770. // plist
  1771. metadataNet.fileName = metadata.fileName;
  1772. metadataNet.fileNameTo = metadata.fileName;
  1773. metadataNet.selector = selectorMovePlist;
  1774. [_queueSelector addObject:metadataNet.selector];
  1775. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1776. }
  1777. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1778. }
  1779. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1780. {
  1781. [_queueSelector removeAllObjects];
  1782. if ([_selectedFileIDsMetadatas count] > 0) {
  1783. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1784. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1785. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1786. } else {
  1787. _numSelectedFileIDsMetadatas = 1;
  1788. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1789. }
  1790. }
  1791. - (void)moveOpenWindow:(NSArray *)indexPaths
  1792. {
  1793. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1794. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1795. viewController.delegate = self;
  1796. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1797. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1798. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1799. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1800. viewController.networkingOperationQueue = app.netQueue;
  1801. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1802. [self presentViewController:navigationController animated:YES completion:nil];
  1803. }
  1804. #pragma --------------------------------------------------------------------------------------------
  1805. #pragma mark ===== Create folder =====
  1806. #pragma --------------------------------------------------------------------------------------------
  1807. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1808. {
  1809. [_hud hideHud];
  1810. if (message)
  1811. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1812. }
  1813. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1814. {
  1815. [_hud hideHud];
  1816. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1817. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1818. // Load Folder or the Datasource
  1819. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1820. [self readFolder:metadataNet.serverUrl];
  1821. } else {
  1822. [self reloadDatasource:metadataNet.serverUrl];
  1823. }
  1824. }
  1825. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1826. {
  1827. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1828. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1829. if (![fileNameFolder length]) return;
  1830. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1831. else metadataNet.serverUrl = _serverUrl;
  1832. metadataNet.action = actionCreateFolder;
  1833. if (autoUploadDirectory)
  1834. metadataNet.options = @"folderAutoUpload";
  1835. metadataNet.fileName = fileNameFolder;
  1836. metadataNet.selector = selectorCreateFolder;
  1837. metadataNet.selectorPost = selectorReadFolderForced;
  1838. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1839. if (!autoUploadDirectory)
  1840. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1841. }
  1842. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1843. {
  1844. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1845. NSString *fileNamePlist;
  1846. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1847. if (![fileNameFolder length]) return;
  1848. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1849. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1850. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1851. // Create folder
  1852. metadataNet.action = actionCreateFolder;
  1853. metadataNet.fileName = fileNamePlist;
  1854. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1855. metadataNet.selector = selectorCreateFolder;
  1856. metadataNet.serverUrl = _serverUrl;
  1857. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1858. // upload plist file
  1859. metadataNet.action = actionUploadOnlyPlist;
  1860. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1861. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1862. metadataNet.selectorPost = selectorReadFolderForced;
  1863. metadataNet.serverUrl = _serverUrl;
  1864. metadataNet.session = k_upload_session_foreground;
  1865. metadataNet.taskStatus = k_taskStatusResume;
  1866. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1867. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1868. }
  1869. - (void)createFolderAutoUpload
  1870. {
  1871. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1872. [self createFolder:autoUploadFileName autoUploadDirectory:YES];
  1873. }
  1874. #pragma --------------------------------------------------------------------------------------------
  1875. #pragma mark ===== Encrypted / Decrypted Folder =====
  1876. #pragma --------------------------------------------------------------------------------------------
  1877. - (void)encyptedDecryptedFolder
  1878. {
  1879. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1880. if (_metadata.cryptated) {
  1881. // DECRYPTED
  1882. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1883. //-------------------------- RENAME -------------------------------------------//
  1884. metadataNet.action = actionMoveFileOrFolder;
  1885. metadataNet.fileID = _metadata.fileID;
  1886. metadataNet.fileName = _metadata.fileNameData;
  1887. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1888. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1889. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1890. metadataNet.selector = selectorRename;
  1891. metadataNet.serverUrl = serverUrl;
  1892. metadataNet.serverUrlTo = serverUrl;
  1893. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1894. //-------------------------- DELETE -------------------------------------------//
  1895. metadataNet.action = actionDeleteFileDirectory;
  1896. metadataNet.fileID = _metadata.fileID;
  1897. metadataNet.fileName = _metadata.fileName;
  1898. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1899. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1900. metadataNet.selector = selectorDeletePlist;
  1901. metadataNet.selectorPost = selectorReadFolderForced;
  1902. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1903. } else {
  1904. // ENCRYPTED
  1905. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1906. // Create File Plist
  1907. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1908. //-------------------------- RENAME -------------------------------------------//
  1909. metadataNet.action = actionMoveFileOrFolder;
  1910. metadataNet.fileID = _metadata.fileID;
  1911. metadataNet.fileName = _metadata.fileName;
  1912. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1913. metadataNet.fileNameTo = fileNameCrypto;
  1914. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1915. metadataNet.selector = selectorRename;
  1916. metadataNet.serverUrl = serverUrl;
  1917. metadataNet.serverUrlTo = serverUrl;
  1918. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1919. //-------------------------- UPLOAD -------------------------------------------//
  1920. metadataNet.action = actionUploadOnlyPlist;
  1921. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1922. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1923. metadataNet.selectorPost = selectorReadFolderForced;
  1924. metadataNet.serverUrl = serverUrl;
  1925. metadataNet.session = k_upload_session_foreground;
  1926. metadataNet.taskStatus = k_taskStatusResume;
  1927. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1928. }
  1929. }
  1930. #pragma --------------------------------------------------------------------------------------------
  1931. #pragma mark ===== Encrypted/Decrypted File =====
  1932. #pragma --------------------------------------------------------------------------------------------
  1933. - (void)encryptedSelectedFiles
  1934. {
  1935. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1936. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1937. for (tableMetadata *metadata in selectedMetadatas) {
  1938. if (metadata.cryptated == NO && metadata.directory == NO)
  1939. [metadatas addObject:metadata];
  1940. }
  1941. if ([metadatas count] > 0) {
  1942. NSLog(@"[LOG] Start encrypted selected files ...");
  1943. for (tableMetadata* metadata in metadatas) {
  1944. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1945. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1946. }
  1947. }
  1948. [self tableViewSelect:NO];
  1949. }
  1950. - (void)decryptedSelectedFiles
  1951. {
  1952. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1953. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1954. for (tableMetadata *metadata in selectedMetadatas) {
  1955. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1956. [metadatas addObject:metadata];
  1957. }
  1958. if ([metadatas count] > 0) {
  1959. NSLog(@"[LOG] Start decrypted selected files ...");
  1960. for (tableMetadata* metadata in metadatas) {
  1961. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1962. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1963. }
  1964. }
  1965. [self tableViewSelect:NO];
  1966. }
  1967. - (void)cmdEncryptedDecryptedFile
  1968. {
  1969. NSString *selector;
  1970. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1971. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1972. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1973. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1974. }
  1975. - (void)encryptedFile:(tableMetadata *)metadata
  1976. {
  1977. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1978. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1979. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1980. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1981. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1982. dispatch_async(dispatch_get_main_queue(), ^{
  1983. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1984. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1985. });
  1986. } else {
  1987. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1988. }
  1989. }
  1990. - (void)decryptedFile:(tableMetadata *)metadata
  1991. {
  1992. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1993. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1994. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1995. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1996. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1997. dispatch_async(dispatch_get_main_queue(), ^{
  1998. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1999. [self performSelector:@selector(reloadDatasource) withObject:nil];
  2000. });
  2001. } else {
  2002. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2003. }
  2004. }
  2005. #pragma --------------------------------------------------------------------------------------------
  2006. #pragma mark ===== Progress & Task Button =====
  2007. #pragma --------------------------------------------------------------------------------------------
  2008. - (void)triggerProgressTask:(NSNotification *)notification
  2009. {
  2010. NSDictionary *dict = notification.userInfo;
  2011. NSString *fileID = [dict valueForKey:@"fileID"];
  2012. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  2013. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  2014. float progress = [[dict valueForKey:@"progress"] floatValue];
  2015. // Check
  2016. if (!fileID)
  2017. return;
  2018. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  2019. if (![serverUrl isEqualToString:_serverUrl])
  2020. return;
  2021. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  2022. if (indexPath) {
  2023. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  2024. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  2025. else cell.progressView.progressTintColor = [UIColor blackColor];
  2026. cell.progressView.hidden = NO;
  2027. [cell.progressView setProgress:progress];
  2028. }
  2029. if (progress == 0)
  2030. [self.navigationController cancelCCProgress];
  2031. else
  2032. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  2033. }
  2034. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  2035. {
  2036. UITouch * touch = [[event allTouches] anyObject];
  2037. CGPoint location = [touch locationInView:self.tableView];
  2038. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2039. if (indexPath) {
  2040. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2041. if (metadata)
  2042. [self reloadTaskButton:metadata];
  2043. }
  2044. }
  2045. - (void)reloadTaskButton:(tableMetadata *)metadata
  2046. {
  2047. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2048. __block NSURLSessionTask *findTask;
  2049. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2050. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2051. NSString *fileID = metadata.fileID;
  2052. // DOWNLOAD
  2053. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2054. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2055. for (NSURLSessionUploadTask *task in downloadTasks)
  2056. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2057. findTask = task;
  2058. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2059. [task cancel];
  2060. }
  2061. if (!findTask) {
  2062. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2063. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2064. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2065. }
  2066. }];
  2067. }
  2068. // UPLOAD
  2069. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2070. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2071. for (NSURLSessionUploadTask *task in uploadTasks)
  2072. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2073. findTask = task;
  2074. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2075. [task cancel];
  2076. }
  2077. if (!findTask) {
  2078. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2079. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2080. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2081. }
  2082. }];
  2083. }
  2084. }
  2085. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2086. {
  2087. UITouch * touch = [[event allTouches] anyObject];
  2088. CGPoint location = [touch locationInView:self.tableView];
  2089. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2090. if (indexPath) {
  2091. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2092. if (metadata)
  2093. [self cancelTaskButton:metadata reloadTable:YES];
  2094. }
  2095. }
  2096. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2097. {
  2098. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2099. __block NSURLSessionTask *findTask;
  2100. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2101. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2102. NSString *fileID = metadata.fileID;
  2103. // DOWNLOAD
  2104. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2105. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2106. for (NSURLSessionTask *task in downloadTasks)
  2107. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2108. findTask = task;
  2109. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2110. [task cancel];
  2111. }
  2112. if (!findTask) {
  2113. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2114. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2115. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2116. }
  2117. }];
  2118. }
  2119. // UPLOAD
  2120. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2121. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2122. for (NSURLSessionUploadTask *task in uploadTasks)
  2123. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2124. findTask = task;
  2125. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2126. [task cancel];
  2127. }
  2128. if (!findTask) {
  2129. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2130. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2131. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2132. }
  2133. }];
  2134. }
  2135. }
  2136. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2137. {
  2138. UITouch * touch = [[event allTouches] anyObject];
  2139. CGPoint location = [touch locationInView:self.tableView];
  2140. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2141. if (indexPath) {
  2142. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2143. if (metadata)
  2144. [self stopTaskButton:metadata];
  2145. }
  2146. }
  2147. - (void)stopTaskButton:(tableMetadata *)metadata
  2148. {
  2149. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2150. __block NSURLSessionTask *findTask;
  2151. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2152. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2153. NSString *fileID = metadata.fileID;
  2154. // UPLOAD
  2155. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2156. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2157. for (NSURLSessionUploadTask *task in uploadTasks)
  2158. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2159. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2160. findTask = task;
  2161. [task cancel];
  2162. }
  2163. if (!findTask) {
  2164. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2165. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2166. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2167. }
  2168. }];
  2169. }
  2170. }
  2171. #pragma --------------------------------------------------------------------------------------------
  2172. #pragma mark ===== Shared =====
  2173. #pragma --------------------------------------------------------------------------------------------
  2174. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2175. {
  2176. [_hud hideHud];
  2177. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2178. // change account ?
  2179. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2180. if([record.account isEqualToString:metadataNet.account] == NO)
  2181. return;
  2182. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2183. if (result) {
  2184. appDelegate.sharesLink = result[0];
  2185. appDelegate.sharesUserAndGroup = result[1];
  2186. }
  2187. // Notify Shares View
  2188. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2189. if (openWindow) {
  2190. if (_shareOC) {
  2191. [_shareOC reloadData];
  2192. } else {
  2193. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2194. // Apriamo la view
  2195. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2196. _shareOC.delegate = self;
  2197. _shareOC.metadata = metadata;
  2198. _shareOC.serverUrl = metadataNet.serverUrl;
  2199. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2200. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2201. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2202. [self presentViewController:_shareOC animated:YES completion:nil];
  2203. }
  2204. }
  2205. [self tableViewReloadData];
  2206. }
  2207. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2208. {
  2209. [_hud hideHud];
  2210. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2211. if (_shareOC)
  2212. [_shareOC reloadData];
  2213. [self tableViewReloadData];
  2214. if (errorCode == 401)
  2215. [self changePasswordAccount];
  2216. }
  2217. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2218. {
  2219. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2220. metadataNet.action = actionShare;
  2221. metadataNet.fileID = metadata.fileID;
  2222. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2223. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2224. metadataNet.password = password;
  2225. metadataNet.selector = selectorShare;
  2226. metadataNet.serverUrl = serverUrl;
  2227. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2228. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2229. }
  2230. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2231. {
  2232. [_hud hideHud];
  2233. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2234. // rimuoviamo la condivisione da db
  2235. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2236. if (result) {
  2237. appDelegate.sharesLink = result[0];
  2238. appDelegate.sharesUserAndGroup = result[1];
  2239. }
  2240. if (_shareOC)
  2241. [_shareOC reloadData];
  2242. [self tableViewReloadData];
  2243. }
  2244. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2245. {
  2246. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2247. metadataNet.action = actionUnShare;
  2248. metadataNet.fileID = metadata.fileID;
  2249. metadataNet.fileName = metadata.fileName;
  2250. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2251. metadataNet.selector = selectorUnshare;
  2252. metadataNet.serverUrl = serverUrl;
  2253. metadataNet.share = share;
  2254. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2255. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2256. }
  2257. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2258. {
  2259. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2260. metadataNet.action = actionUpdateShare;
  2261. metadataNet.fileID = metadata.fileID;
  2262. metadataNet.expirationTime = expirationTime;
  2263. metadataNet.password = password;
  2264. metadataNet.selector = selectorUpdateShare;
  2265. metadataNet.serverUrl = serverUrl;
  2266. metadataNet.share = share;
  2267. metadataNet.sharePermission = permission;
  2268. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2269. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2270. }
  2271. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2272. {
  2273. [_hud hideHud];
  2274. if (_shareOC)
  2275. [_shareOC reloadUserAndGroup:items];
  2276. }
  2277. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2278. {
  2279. [_hud hideHud];
  2280. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2281. }
  2282. - (void)getUserAndGroup:(NSString *)find
  2283. {
  2284. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2285. metadataNet.action = actionGetUserAndGroup;
  2286. metadataNet.options = find;
  2287. metadataNet.selector = selectorGetUserAndGroup;
  2288. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2289. [_hud visibleIndeterminateHud];
  2290. }
  2291. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2292. {
  2293. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2294. metadataNet.action = actionShareWith;
  2295. metadataNet.fileID = metadata.fileID;
  2296. metadataNet.directoryID = directoryID;
  2297. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2298. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2299. metadataNet.serverUrl = serverUrl;
  2300. metadataNet.selector = selectorShare;
  2301. metadataNet.share = user;
  2302. metadataNet.shareeType = shareeType;
  2303. metadataNet.sharePermission = permission;
  2304. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2305. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2306. }
  2307. - (void)openWindowShare:(tableMetadata *)metadata
  2308. {
  2309. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2310. metadataNet.action = actionReadShareServer;
  2311. metadataNet.fileID = metadata.fileID;
  2312. metadataNet.fileName = metadata.fileName;
  2313. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2314. metadataNet.selector = selectorOpenWindowShare;
  2315. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2316. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2317. [_hud visibleIndeterminateHud];
  2318. }
  2319. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2320. {
  2321. CGPoint location = [tapGesture locationInView:self.tableView];
  2322. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2323. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2324. if (metadata)
  2325. [self openWindowShare:metadata];
  2326. }
  2327. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2328. {
  2329. CGPoint location = [tapGesture locationInView:self.tableView];
  2330. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2331. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2332. if (metadata) {
  2333. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2334. vc.metadata = metadata;
  2335. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2336. [self presentViewController:vc animated:YES completion:nil];
  2337. }
  2338. }
  2339. #pragma --------------------------------------------------------------------------------------------
  2340. #pragma mark ===== Favorite =====
  2341. #pragma --------------------------------------------------------------------------------------------
  2342. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2343. {
  2344. _dateReadDataSource = nil;
  2345. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2346. if (_isSearchMode)
  2347. [self readFolder:metadataNet.serverUrl];
  2348. else
  2349. [self reloadDatasource:metadataNet.serverUrl];
  2350. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2351. if (metadata.directory && metadata.favorite) {
  2352. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2353. [app.activeFavorites addFavoriteFolder:dir];
  2354. }
  2355. }
  2356. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2357. {
  2358. }
  2359. - (void)addFavorite:(tableMetadata *)metadata
  2360. {
  2361. if (metadata.directory) {
  2362. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2363. } else {
  2364. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2365. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2366. }
  2367. }
  2368. - (void)removeFavorite:(tableMetadata *)metadata
  2369. {
  2370. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2371. }
  2372. #pragma --------------------------------------------------------------------------------------------
  2373. #pragma mark ===== Local =====
  2374. #pragma --------------------------------------------------------------------------------------------
  2375. - (void)addLocal:(tableMetadata *)metadata
  2376. {
  2377. if (metadata.errorPasscode || !metadata.uuid) return;
  2378. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2379. if ([metadata.type isEqualToString: k_metadataType_file])
  2380. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2381. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2382. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2383. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2384. }
  2385. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2386. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2387. }
  2388. #pragma --------------------------------------------------------------------------------------------
  2389. #pragma mark ===== Open in... =====
  2390. #pragma --------------------------------------------------------------------------------------------
  2391. - (void)openIn:(tableMetadata *)metadata
  2392. {
  2393. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2394. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2395. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2396. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2397. }
  2398. #pragma --------------------------------------------------------------------------------------------
  2399. #pragma mark ===== Remove Local File =====
  2400. #pragma --------------------------------------------------------------------------------------------
  2401. - (void)removeLocalFile:(tableMetadata *)metadata
  2402. {
  2403. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2404. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2405. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2406. [self reloadDatasource:serverUrl];
  2407. }
  2408. #pragma --------------------------------------------------------------------------------------------
  2409. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2410. #pragma --------------------------------------------------------------------------------------------
  2411. - (void)orderTable:(NSString *)order
  2412. {
  2413. [CCUtility setOrderSettings:order];
  2414. // Clear data-read of DataSource
  2415. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2416. }
  2417. - (void)ascendingTable:(BOOL)ascending
  2418. {
  2419. [CCUtility setAscendingSettings:ascending];
  2420. // Clear data-read of DataSource
  2421. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2422. }
  2423. - (void)directoryOnTop:(BOOL)directoryOnTop
  2424. {
  2425. [CCUtility setDirectoryOnTop:directoryOnTop];
  2426. // Clear data-read of DataSource
  2427. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2428. }
  2429. - (void)tableGroupBy:(NSString *)groupBy
  2430. {
  2431. [CCUtility setGroupBySettings:groupBy];
  2432. // Clear data-read of DataSource
  2433. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2434. }
  2435. #pragma --------------------------------------------------------------------------------------------
  2436. #pragma mark ==== Menu LOGO ====
  2437. #pragma --------------------------------------------------------------------------------------------
  2438. - (void)menuLogo
  2439. {
  2440. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2441. return;
  2442. // Brand
  2443. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2444. return;
  2445. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutoUploadWithSession:nil] > 0) {
  2446. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2447. return;
  2448. }
  2449. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2450. NSMutableArray *menuArray = [NSMutableArray new];
  2451. for (NSString *account in listAccount) {
  2452. if ([account isEqualToString:app.activeAccount]) continue;
  2453. CCMenuItem *item = [[CCMenuItem alloc] init];
  2454. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2455. item.argument = account;
  2456. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2457. item.target = self;
  2458. item.action = @selector(changeDefaultAccount:);
  2459. [menuArray addObject:item];
  2460. }
  2461. if ([menuArray count] == 0)
  2462. return;
  2463. OptionalConfiguration options;
  2464. Color textColor, backgroundColor;
  2465. textColor.R = 0;
  2466. textColor.G = 0;
  2467. textColor.B = 0;
  2468. backgroundColor.R = 1;
  2469. backgroundColor.G = 1;
  2470. backgroundColor.B = 1;
  2471. NSInteger originY = 60;
  2472. options.arrowSize = 9;
  2473. options.marginXSpacing = 7;
  2474. options.marginYSpacing = 10;
  2475. options.intervalSpacing = 20;
  2476. options.menuCornerRadius = 6.5;
  2477. options.maskToBackground = NO;
  2478. options.shadowOfMenu = YES;
  2479. options.hasSeperatorLine = YES;
  2480. options.seperatorLineHasInsets = YES;
  2481. options.textColor = textColor;
  2482. options.menuBackgroundColor = backgroundColor;
  2483. CGRect rect = self.view.frame;
  2484. rect.origin.y = rect.origin.y + originY;
  2485. rect.size.height = rect.size.height - originY;
  2486. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2487. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2488. }
  2489. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2490. {
  2491. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2492. // STOP, erase all in queue networking
  2493. [app cancelAllOperations];
  2494. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2495. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2496. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2497. if (tableAccount)
  2498. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2499. // go to home sweet home
  2500. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2501. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2502. });
  2503. }
  2504. #pragma --------------------------------------------------------------------------------------------
  2505. #pragma mark ==== ReMenu ====
  2506. #pragma --------------------------------------------------------------------------------------------
  2507. - (void)createReMenuBackgroundView:(REMenu *)menu
  2508. {
  2509. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2510. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2511. [UIView animateWithDuration:0.2 animations:^{
  2512. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2513. if (height < self.tabBarController.tabBar.frame.size.height)
  2514. height = self.tabBarController.tabBar.frame.size.height;
  2515. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2516. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2517. }];
  2518. }
  2519. - (void)createReMainMenu
  2520. {
  2521. NSString *ordinamento;
  2522. NSString *groupBy = _directoryGroupBy;
  2523. __block NSString *nuovoOrdinamento;
  2524. NSString *titoloNuovo, *titoloAttuale;
  2525. BOOL ascendente;
  2526. __block BOOL nuovoAscendente;
  2527. UIImage *image;
  2528. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2529. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2530. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2531. [self tableViewSelect:YES];
  2532. }
  2533. }];
  2534. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2535. ordinamento = _directoryOrder;
  2536. if ([ordinamento isEqualToString:@"fileName"]) {
  2537. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2538. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2539. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2540. nuovoOrdinamento = @"date";
  2541. }
  2542. if ([ordinamento isEqualToString:@"date"]) {
  2543. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2544. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2545. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2546. nuovoOrdinamento = @"fileName";
  2547. }
  2548. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2549. [self orderTable:nuovoOrdinamento];
  2550. }];
  2551. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2552. ascendente = [CCUtility getAscendingSettings];
  2553. if (ascendente) {
  2554. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2555. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2556. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2557. nuovoAscendente = false;
  2558. }
  2559. if (!ascendente) {
  2560. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2561. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2562. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2563. nuovoAscendente = true;
  2564. }
  2565. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2566. [self ascendingTable:nuovoAscendente];
  2567. }];
  2568. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2569. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2570. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2571. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2572. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2573. else [self tableGroupBy:@"alphabetic"];
  2574. }];
  2575. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2576. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2577. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2578. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2579. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2580. else [self tableGroupBy:@"typefile"];
  2581. }];
  2582. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2583. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2584. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2585. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2586. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2587. else [self tableGroupBy:@"date"];
  2588. }];
  2589. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2590. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2591. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2592. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2593. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2594. else [self directoryOnTop:YES];
  2595. }];
  2596. // REMENU --------------------------------------------------------------------------------------------------------------
  2597. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2598. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2599. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2600. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2601. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2602. app.reMainMenu.separatorHeight = 0.5;
  2603. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2604. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2605. app.reMainMenu.textColor = [UIColor blackColor];
  2606. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2607. app.reMainMenu.textShadowColor = nil;
  2608. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2609. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2610. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2611. app.reMainMenu.highlightedSeparatorColor = nil;
  2612. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2613. app.reMainMenu.highlightedTextShadowColor = nil;
  2614. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2615. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2616. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2617. app.reMainMenu.subtitleTextShadowColor = nil;
  2618. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2619. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2620. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2621. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2622. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2623. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2624. app.reMainMenu.borderWidth = 0.3;
  2625. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2626. app.reMainMenu.animationDuration = 0.2;
  2627. app.reMainMenu.closeAnimationDuration = 0.2;
  2628. app.reMainMenu.bounce = NO;
  2629. [app.reMainMenu setClosePreparationBlock:^{
  2630. // Backgroun reMenu (Gesture)
  2631. [_reMenuBackgroundView removeFromSuperview];
  2632. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2633. }];
  2634. }
  2635. - (void)toggleReMainMenu
  2636. {
  2637. if (app.reMainMenu.isOpen) {
  2638. [app.reMainMenu close];
  2639. } else {
  2640. [self createReMainMenu];
  2641. [app.reMainMenu showFromNavigationController:self.navigationController];
  2642. // Backgroun reMenu & (Gesture)
  2643. [self createReMenuBackgroundView:app.reMainMenu];
  2644. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2645. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2646. }
  2647. }
  2648. - (void)createReSelectMenu
  2649. {
  2650. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2651. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2652. [self deleteFile];
  2653. }];
  2654. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2655. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2656. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2657. }];
  2658. if (app.isCryptoCloudMode) {
  2659. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2660. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2661. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2662. }];
  2663. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2664. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2665. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2666. }];
  2667. }
  2668. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2669. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2670. [self downloadSelectedFilesFolders];
  2671. }];
  2672. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2673. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2674. [self saveSelectedFiles];
  2675. }];
  2676. // REMENU --------------------------------------------------------------------------------------------------------------
  2677. if (app.isCryptoCloudMode) {
  2678. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2679. } else {
  2680. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2681. }
  2682. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2683. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2684. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2685. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2686. app.reSelectMenu.separatorHeight = 0.5;
  2687. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2688. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2689. app.reSelectMenu.textColor = [UIColor blackColor];
  2690. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2691. app.reSelectMenu.textShadowColor = nil;
  2692. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2693. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2694. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2695. app.reSelectMenu.highlightedSeparatorColor = nil;
  2696. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2697. app.reSelectMenu.highlightedTextShadowColor = nil;
  2698. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2699. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2700. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2701. app.reSelectMenu.subtitleTextShadowColor = nil;
  2702. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2703. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2704. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2705. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2706. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2707. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2708. app.reSelectMenu.borderWidth = 0.3;
  2709. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2710. app.reSelectMenu.closeAnimationDuration = 0.2;
  2711. app.reSelectMenu.animationDuration = 0.2;
  2712. app.reSelectMenu.bounce = NO;
  2713. [app.reSelectMenu setClosePreparationBlock:^{
  2714. // Backgroun reMenu (Gesture)
  2715. [_reMenuBackgroundView removeFromSuperview];
  2716. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2717. }];
  2718. }
  2719. - (void)toggleReSelectMenu
  2720. {
  2721. if (app.reSelectMenu.isOpen) {
  2722. [app.reSelectMenu close];
  2723. } else {
  2724. [self createReSelectMenu];
  2725. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2726. // Backgroun reMenu & (Gesture)
  2727. [self createReMenuBackgroundView:app.reSelectMenu];
  2728. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2729. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2730. }
  2731. }
  2732. #pragma --------------------------------------------------------------------------------------------
  2733. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2734. #pragma --------------------------------------------------------------------------------------------
  2735. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2736. {
  2737. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2738. UITableView *tableView = (UITableView*)self.view;
  2739. CGPoint touchPoint = [recognizer locationInView:self.view];
  2740. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2741. if (indexPath)
  2742. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2743. else
  2744. _metadata = nil;
  2745. [self becomeFirstResponder];
  2746. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2747. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2748. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2749. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2750. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2751. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2752. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2753. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2754. if (app.isCryptoCloudMode)
  2755. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2756. else
  2757. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2758. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2759. [menuController setMenuVisible:YES animated:YES];
  2760. }
  2761. }
  2762. - (BOOL)canBecomeFirstResponder
  2763. {
  2764. return YES;
  2765. }
  2766. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2767. {
  2768. // For copy file, copy files, Open in ... :
  2769. //
  2770. // NO Directory
  2771. // NO Error Passcode
  2772. // NO In Session mode (download/upload)
  2773. // NO Template
  2774. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2775. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2776. // NO Cryptated with Title lenght = 0
  2777. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2778. return YES;
  2779. }
  2780. return NO;
  2781. }
  2782. if (@selector(copyFiles:) == action) {
  2783. if (_isSelectedMode) {
  2784. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2785. for (tableMetadata *metadata in selectedMetadatas) {
  2786. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2787. // NO Cryptated with Title lenght = 0
  2788. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2789. return YES;
  2790. }
  2791. }
  2792. }
  2793. return NO;
  2794. }
  2795. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2796. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2797. NSArray *items = [pasteboard items];
  2798. if ([items count] == 1) {
  2799. // Value : (NSData) fileID
  2800. NSDictionary *dic = [items objectAtIndex:0];
  2801. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2802. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2803. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2804. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2805. if (directoryUser) {
  2806. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2807. return YES;
  2808. }
  2809. return NO;
  2810. } else return NO;
  2811. }
  2812. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2813. BOOL isValid = NO;
  2814. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2815. NSArray *items = [pasteboard items];
  2816. if ([items count] <= 1) return NO;
  2817. for (NSDictionary *dic in items) {
  2818. // Value : (NSData) fileID
  2819. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2820. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2821. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2822. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2823. if (directoryUser) {
  2824. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2825. isValid = YES;
  2826. }
  2827. }
  2828. return isValid;
  2829. }
  2830. return NO;
  2831. }
  2832. /************************************ COPY ************************************/
  2833. - (void)copyFile:(id)sender
  2834. {
  2835. // Remove all item
  2836. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2837. pasteboard.items = [[NSArray alloc] init];
  2838. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2839. [self copyFileToPasteboard:_metadata];
  2840. } else {
  2841. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2842. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2843. }
  2844. }
  2845. - (void)copyFiles:(id)sender
  2846. {
  2847. // Remove all item
  2848. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2849. pasteboard.items = [[NSArray alloc] init];
  2850. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2851. for (tableMetadata *metadata in selectedMetadatas) {
  2852. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2853. [self copyFileToPasteboard:metadata];
  2854. } else {
  2855. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2856. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2857. }
  2858. }
  2859. [self tableViewSelect:NO];
  2860. }
  2861. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2862. {
  2863. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2864. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2865. // Value : (NSData) fileID
  2866. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2867. [items addObject:item];
  2868. [pasteboard setItems:items];
  2869. }
  2870. /************************************ OPEN IN ... ************************************/
  2871. - (void)openinFile:(id)sender
  2872. {
  2873. [self openIn:_metadata];
  2874. }
  2875. /************************************ PASTE ************************************/
  2876. - (void)pasteFile:(id)sender
  2877. {
  2878. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2879. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2880. }
  2881. - (void)pasteFileEncrypted:(id)sender
  2882. {
  2883. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2884. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2885. }
  2886. - (void)pasteFiles:(id)sender
  2887. {
  2888. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2889. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2890. }
  2891. - (void)pasteFilesEncrypted:(id)sender
  2892. {
  2893. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2894. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2895. }
  2896. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2897. {
  2898. for (NSDictionary *dic in items) {
  2899. // Value : (NSData) fileID
  2900. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2901. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2902. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2903. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2904. if (!metadata || !account) return;
  2905. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2906. if (directoryUser) {
  2907. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2908. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2909. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2910. }
  2911. }
  2912. }
  2913. }
  2914. #pragma --------------------------------------------------------------------------------------------
  2915. #pragma mark ===== Lock Passcode =====
  2916. #pragma --------------------------------------------------------------------------------------------
  2917. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2918. {
  2919. return _failedAttempts;
  2920. }
  2921. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2922. {
  2923. return _lockUntilDate;
  2924. }
  2925. - (void)passcodeViewCloseButtonPressed:(id)sender
  2926. {
  2927. [self dismissViewControllerAnimated:YES completion:nil];
  2928. }
  2929. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2930. {
  2931. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2932. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2933. _lockUntilDate = nil;
  2934. _failedAttempts = 0;
  2935. aResultHandler(YES);
  2936. } else aResultHandler(NO);
  2937. } else aResultHandler(YES);
  2938. }
  2939. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2940. {
  2941. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2942. switch (aViewController.type) {
  2943. case BKPasscodeViewControllerCheckPasscodeType: {
  2944. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2945. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2946. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2947. // scriviamo il passcode
  2948. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2949. [self readFolder:_serverUrl];
  2950. } else {
  2951. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2952. [alertView show];
  2953. }
  2954. }
  2955. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2956. // possiamo procedere alla prossima directory
  2957. [self performSegueDirectoryWithControlPasscode:false];
  2958. // avviamo la sessione Passcode Lock con now
  2959. app.sessionePasscodeLock = [NSDate date];
  2960. }
  2961. // disattivazione lock cartella
  2962. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2963. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2964. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2965. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2966. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2967. }
  2968. [self tableViewReloadData];
  2969. }
  2970. }
  2971. break;
  2972. default:
  2973. break;
  2974. }
  2975. }
  2976. - (void)comandoLockPassword
  2977. {
  2978. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2979. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2980. // se non è abilitato il Lock Passcode esci
  2981. if ([[CCUtility getBlockCode] length] == 0) {
  2982. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2983. [alertView show];
  2984. return;
  2985. }
  2986. // se è richiesta la disattivazione si chiede la password
  2987. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2988. if (directory.lock) {
  2989. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2990. viewController.delegate = self;
  2991. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2992. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2993. viewController.inputViewTitlePassword = YES;
  2994. if ([CCUtility getSimplyBlockCode]) {
  2995. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2996. viewController.passcodeInputView.maximumLength = 6;
  2997. } else {
  2998. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2999. viewController.passcodeInputView.maximumLength = 64;
  3000. }
  3001. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3002. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3003. viewController.touchIDManager = touchIDManager;
  3004. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  3005. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3006. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3007. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3008. [self presentViewController:navigationController animated:YES completion:nil];
  3009. return;
  3010. }
  3011. // ---------------- ACTIVATE PASSWORD
  3012. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  3013. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3014. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3015. } else {
  3016. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3017. }
  3018. }
  3019. #pragma mark -
  3020. #pragma --------------------------------------------------------------------------------------------
  3021. #pragma mark ===== Swipe Tablet -> menu =====
  3022. #pragma --------------------------------------------------------------------------------------------
  3023. //Nothing gets called here if you invoke `tableView:editActionsForRowAtIndexPath:` according to Apple docs so just leave this method blank
  3024. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3025. {
  3026. }
  3027. // the cells you would like the actions to appear needs to be editable
  3028. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3029. {
  3030. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3031. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3032. return NO;
  3033. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0)
  3034. return NO;
  3035. return YES;
  3036. }
  3037. - (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
  3038. {
  3039. NSLog(@"Open");
  3040. }
  3041. - (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
  3042. {
  3043. NSLog(@"Close");
  3044. }
  3045. - (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
  3046. {
  3047. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3048. // ---- DELETE ----
  3049. UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:NSLocalizedString(@"_delete_", nil) handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
  3050. // Directory locked ?
  3051. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3052. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3053. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  3054. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3055. return;
  3056. }
  3057. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3058. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  3059. [self performSelector:@selector(deleteFile) withObject:nil];
  3060. }]];
  3061. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3062. [alertController dismissViewControllerAnimated:YES completion:nil];
  3063. }]];
  3064. alertController.popoverPresentationController.sourceView = self.view;
  3065. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3066. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3067. [alertController.view layoutIfNeeded];
  3068. [self presentViewController:alertController animated:YES completion:nil];
  3069. }];
  3070. // ---- MORE ----
  3071. UITableViewRowAction *more = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:NSLocalizedString(@"_more_", nil) handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
  3072. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3073. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  3074. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3075. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3076. if (_metadata.favorite) {
  3077. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3078. } else {
  3079. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3080. }
  3081. if (_metadata.directory) {
  3082. // calcolo lockServerUrl
  3083. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3084. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3085. if (directory.lock)
  3086. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3087. else
  3088. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3089. }
  3090. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  3091. /******************************************* AHKActionSheet *******************************************/
  3092. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3093. actionSheet.animationDuration = 0.2;
  3094. actionSheet.blurRadius = 0.0f;
  3095. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3096. actionSheet.buttonHeight = 50.0;
  3097. actionSheet.cancelButtonHeight = 50.0f;
  3098. actionSheet.separatorHeight = 5.0f;
  3099. actionSheet.automaticallyTintButtonImages = @(NO);
  3100. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3101. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3102. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3103. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3104. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3105. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3106. /******************************************* DIRECTORY *******************************************/
  3107. if (_metadata.directory) {
  3108. BOOL lockDirectory = NO;
  3109. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3110. // Directory bloccata ?
  3111. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3112. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3113. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3114. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3115. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3116. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3117. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3118. height: 50.0
  3119. type: AHKActionSheetButtonTypeDisabled
  3120. handler: nil
  3121. ];
  3122. if (!lockDirectory && !_metadata.cryptated) {
  3123. [actionSheet addButtonWithTitle:titleFavorite
  3124. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3125. backgroundColor:[UIColor whiteColor]
  3126. height: 50.0
  3127. type:AHKActionSheetButtonTypeDefault
  3128. handler:^(AHKActionSheet *as) {
  3129. // close swipe
  3130. [self setEditing:NO animated:YES];
  3131. if (_metadata.favorite)
  3132. [self removeFavorite:_metadata];
  3133. else
  3134. [self addFavorite:_metadata];
  3135. }];
  3136. }
  3137. if (_metadata.cryptated == NO && !lockDirectory) {
  3138. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3139. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3140. backgroundColor:[UIColor whiteColor]
  3141. height: 50.0
  3142. type:AHKActionSheetButtonTypeDefault
  3143. handler:^(AHKActionSheet *as) {
  3144. // close swipe
  3145. [self setEditing:NO animated:YES];
  3146. [self openWindowShare:_metadata];
  3147. }];
  3148. }
  3149. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3150. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3151. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3152. backgroundColor:[UIColor whiteColor]
  3153. height: 50.0
  3154. type:AHKActionSheetButtonTypeDefault
  3155. handler:^(AHKActionSheet *as) {
  3156. // close swipe
  3157. [self setEditing:NO animated:YES];
  3158. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3159. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3160. textField.text = _metadata.fileNamePrint;
  3161. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  3162. //textField.delegate = self;
  3163. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3164. }];
  3165. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3166. NSLog(@"Cancel action");
  3167. }];
  3168. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3169. UITextField *fileName = alertController.textFields.firstObject;
  3170. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3171. }];
  3172. okAction.enabled = NO;
  3173. [alertController addAction:cancelAction];
  3174. [alertController addAction:okAction];
  3175. [self presentViewController:alertController animated:YES completion:nil];
  3176. }];
  3177. }
  3178. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3179. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3180. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3181. backgroundColor:[UIColor whiteColor]
  3182. height: 50.0
  3183. type:AHKActionSheetButtonTypeDefault
  3184. handler:^(AHKActionSheet *as) {
  3185. // close swipe
  3186. [self setEditing:NO animated:YES];
  3187. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3188. }];
  3189. }
  3190. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3191. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3192. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3193. backgroundColor:[UIColor whiteColor]
  3194. height: 50.0
  3195. type:AHKActionSheetButtonTypeDefault
  3196. handler:^(AHKActionSheet *as) {
  3197. // close swipe
  3198. [self setEditing:NO animated:YES];
  3199. // Settings new folder Automatatic upload
  3200. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3201. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3202. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3203. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3204. if (app.activeAccount.length > 0 && app.activePhotos)
  3205. [app.activePhotos reloadDatasourceForced];
  3206. [self readFolder:serverUrl];
  3207. NSLog(@"[LOG] Update Folder Photo");
  3208. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3209. if ([autoUploadPath length] > 0)
  3210. [[CCSynchronize sharedSynchronize] synchronizedFolder:autoUploadPath selector:selectorReadFolder];
  3211. }];
  3212. }
  3213. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3214. [actionSheet addButtonWithTitle:titoloLock
  3215. image:[UIImage imageNamed:@"actionSheetLock"]
  3216. backgroundColor:[UIColor whiteColor]
  3217. height: 50.0
  3218. type:AHKActionSheetButtonTypeEncrypted
  3219. handler:^(AHKActionSheet *as) {
  3220. // close swipe
  3221. [self setEditing:NO animated:YES];
  3222. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3223. }];
  3224. }
  3225. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3226. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3227. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3228. backgroundColor:[UIColor whiteColor]
  3229. height: 50.0
  3230. type:AHKActionSheetButtonTypeEncrypted
  3231. handler:^(AHKActionSheet *as) {
  3232. // close swipe
  3233. [self setEditing:NO animated:YES];
  3234. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3235. }];
  3236. }
  3237. [actionSheet show];
  3238. }
  3239. /******************************************* FILE *******************************************/
  3240. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3241. UIImage *iconHeader;
  3242. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3243. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3244. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3245. else
  3246. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3247. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3248. image: iconHeader
  3249. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3250. height: 50.0
  3251. type: AHKActionSheetButtonTypeDisabled
  3252. handler: nil
  3253. ];
  3254. if (!_metadata.cryptated) {
  3255. [actionSheet addButtonWithTitle:titleFavorite
  3256. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3257. backgroundColor:[UIColor whiteColor]
  3258. height: 50.0
  3259. type:AHKActionSheetButtonTypeDefault
  3260. handler:^(AHKActionSheet *as) {
  3261. // close swipe
  3262. [self setEditing:NO animated:YES];
  3263. if (_metadata.favorite)
  3264. [self removeFavorite:_metadata];
  3265. else
  3266. [self addFavorite:_metadata];
  3267. }];
  3268. }
  3269. if (_metadata.cryptated == NO) {
  3270. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3271. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3272. backgroundColor:[UIColor whiteColor]
  3273. height: 50.0
  3274. type:AHKActionSheetButtonTypeDefault
  3275. handler:^(AHKActionSheet *as) {
  3276. // close swipe
  3277. [self setEditing:NO animated:YES];
  3278. [self openWindowShare:_metadata];
  3279. }];
  3280. }
  3281. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3282. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3283. backgroundColor:[UIColor whiteColor]
  3284. height: 50.0
  3285. type:AHKActionSheetButtonTypeDefault
  3286. handler:^(AHKActionSheet *as) {
  3287. // close swipe
  3288. [self setEditing:NO animated:YES];
  3289. [self performSelector:@selector(openIn:) withObject:_metadata];
  3290. }];
  3291. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3292. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3293. backgroundColor:[UIColor whiteColor]
  3294. height: 50.0
  3295. type:AHKActionSheetButtonTypeDefault
  3296. handler:^(AHKActionSheet *as) {
  3297. // close swipe
  3298. [self setEditing:NO animated:YES];
  3299. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3300. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3301. //textField.placeholder = _metadata.fileNamePrint;
  3302. textField.text = _metadata.fileNamePrint;
  3303. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3304. }];
  3305. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3306. NSLog(@"Cancel action");
  3307. }];
  3308. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3309. UITextField *fileName = alertController.textFields.firstObject;
  3310. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3311. }];
  3312. okAction.enabled = NO;
  3313. [alertController addAction:cancelAction];
  3314. [alertController addAction:okAction];
  3315. [self presentViewController:alertController animated:YES completion:nil];
  3316. }];
  3317. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3318. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3319. backgroundColor:[UIColor whiteColor]
  3320. height: 50.0
  3321. type:AHKActionSheetButtonTypeDefault
  3322. handler:^(AHKActionSheet *as) {
  3323. // close swipe
  3324. [self setEditing:NO animated:YES];
  3325. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3326. }];
  3327. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3328. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3329. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3330. backgroundColor:[UIColor whiteColor]
  3331. height: 50.0
  3332. type:AHKActionSheetButtonTypeDefault
  3333. handler:^(AHKActionSheet *as) {
  3334. // close swipe
  3335. [self setEditing:NO animated:YES];
  3336. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3337. }];
  3338. }
  3339. if (app.isCryptoCloudMode) {
  3340. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3341. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3342. backgroundColor:[UIColor whiteColor]
  3343. height: 50.0
  3344. type:AHKActionSheetButtonTypeEncrypted
  3345. handler:^(AHKActionSheet *as) {
  3346. // close swipe
  3347. [self setEditing:NO animated:YES];
  3348. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3349. }];
  3350. }
  3351. [actionSheet show];
  3352. }
  3353. /******************************************* TEMPLATE *******************************************/
  3354. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3355. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3356. image: [UIImage imageNamed:_metadata.iconName]
  3357. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3358. height: 50.0
  3359. type: AHKActionSheetButtonTypeDisabled
  3360. handler: nil
  3361. ];
  3362. if ([_metadata.model isEqualToString:@"note"]) {
  3363. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3364. image:[UIImage imageNamed:@"actionSheetRename"]
  3365. backgroundColor:[UIColor whiteColor]
  3366. height: 50.0
  3367. type:AHKActionSheetButtonTypeDefault
  3368. handler:^(AHKActionSheet *as) {
  3369. // close swipe
  3370. [self setEditing:NO animated:YES];
  3371. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3372. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3373. textField.placeholder = _metadata.fileNamePrint;
  3374. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3375. }];
  3376. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3377. NSLog(@"Cancel action");
  3378. }];
  3379. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3380. UITextField *fileName = alertController.textFields.firstObject;
  3381. [self performSelectorOnMainThread:@selector(renameNote:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3382. }];
  3383. okAction.enabled = NO;
  3384. [alertController addAction:cancelAction];
  3385. [alertController addAction:okAction];
  3386. [self presentViewController:alertController animated:YES completion:nil];
  3387. }];
  3388. }
  3389. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3390. image:[UIImage imageNamed:@"actionSheetMove"]
  3391. backgroundColor:[UIColor whiteColor]
  3392. height: 50.0
  3393. type:AHKActionSheetButtonTypeDefault
  3394. handler:^(AHKActionSheet *as) {
  3395. // close swipe
  3396. [self setEditing:NO animated:YES];
  3397. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3398. }];
  3399. [actionSheet show];
  3400. }
  3401. }];
  3402. more.backgroundColor = [UIColor lightGrayColor];
  3403. return @[delete, more];
  3404. }
  3405. #pragma --------------------------------------------------------------------------------------------
  3406. #pragma mark - ==== Datasource ====
  3407. #pragma --------------------------------------------------------------------------------------------
  3408. - (void)clearDateReadDataSource:(NSNotification *)notification
  3409. {
  3410. _dateReadDataSource = Nil;
  3411. [self reloadDatasource];
  3412. }
  3413. - (void)reloadDatasource
  3414. {
  3415. [self reloadDatasource:_serverUrl];
  3416. }
  3417. - (void)reloadDatasource:(NSString *)serverUrl
  3418. {
  3419. // test
  3420. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3421. return;
  3422. // Search Mode
  3423. if(_isSearchMode) {
  3424. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3425. [self tableViewReloadData];
  3426. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3427. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3428. _noFilesSearchDescription = @"";
  3429. }
  3430. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3431. _noFilesSearchTitle = @"";
  3432. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3433. }
  3434. [self.tableView reloadEmptyDataSet];
  3435. return;
  3436. }
  3437. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3438. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3439. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3440. if (main) {
  3441. [main reloadDatasource];
  3442. } else {
  3443. [self tableViewReloadData];
  3444. [app.activeTransfers reloadDatasource];
  3445. }
  3446. return;
  3447. }
  3448. [app.activeTransfers reloadDatasource];
  3449. // Settaggio variabili per le ottimizzazioni
  3450. _directoryGroupBy = [CCUtility getGroupBySettings];
  3451. _directoryOrder = [CCUtility getOrderSettings];
  3452. // Controllo data lettura Data Source
  3453. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl == %@", serverUrl]];
  3454. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3455. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3456. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3457. _dateReadDataSource = [NSDate date];
  3458. // Data Source
  3459. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3460. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3461. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3462. } else {
  3463. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3464. }
  3465. [self tableViewReloadData];
  3466. }
  3467. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3468. {
  3469. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3470. if (selectedRows.count > 0) {
  3471. for (NSIndexPath *selectionIndex in selectedRows) {
  3472. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3473. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3474. [metadatas addObject:metadata];
  3475. }
  3476. }
  3477. return metadatas;
  3478. }
  3479. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3480. {
  3481. NSInteger section = indexPath.section + 1;
  3482. NSInteger row = indexPath.row + 1;
  3483. NSInteger totSections =[_sectionDataSource.sections count] ;
  3484. if ((totSections < section) || (section > totSections)) {
  3485. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3486. return nil;
  3487. }
  3488. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3489. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3490. if (fileIDs) {
  3491. NSInteger totRows =[fileIDs count] ;
  3492. if ((totRows < row) || (row > totRows)) {
  3493. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3494. return nil;
  3495. }
  3496. } else {
  3497. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3498. return nil;
  3499. }
  3500. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3501. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3502. return metadata;
  3503. }
  3504. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3505. {
  3506. NSInteger totSections =[_sectionDataSource.sections count] ;
  3507. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3508. #if DEBUG
  3509. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3510. [alertView show];
  3511. #endif
  3512. return nil;
  3513. }
  3514. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3515. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3516. }
  3517. #pragma --------------------------------------------------------------------------------------------
  3518. #pragma mark - ==== Table ====
  3519. #pragma --------------------------------------------------------------------------------------------
  3520. - (void)tableViewSelect:(BOOL)edit
  3521. {
  3522. // chiudiamo eventuali swipe aperti
  3523. if (edit)
  3524. [self.tableView setEditing:NO animated:NO];
  3525. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3526. [self.tableView setEditing:edit animated:YES];
  3527. _isSelectedMode = edit;
  3528. if (edit)
  3529. [self setUINavigationBarSelected];
  3530. else
  3531. [self setUINavigationBarDefault];
  3532. [_selectedFileIDsMetadatas removeAllObjects];
  3533. [self setTitle];
  3534. }
  3535. - (void)tableViewReloadData
  3536. {
  3537. // store selected cells before relod
  3538. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3539. // reload table view
  3540. [self.tableView reloadData];
  3541. // selected cells stored
  3542. for (NSIndexPath *path in indexPaths)
  3543. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3544. [self setTableViewFooter];
  3545. if (self.tableView.editing)
  3546. [self setTitle];
  3547. }
  3548. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3549. {
  3550. return 60;
  3551. }
  3552. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3553. {
  3554. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3555. }
  3556. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3557. {
  3558. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3559. }
  3560. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3561. {
  3562. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3563. NSString *sectionTitle = [sections objectAtIndex:section];
  3564. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3565. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3566. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3567. return 20.f;
  3568. }
  3569. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3570. {
  3571. float shift;
  3572. UIVisualEffectView *visualEffectView;
  3573. // Titolo
  3574. NSString *titleSection;
  3575. // Controllo
  3576. if ([_sectionDataSource.sections count] == 0)
  3577. return nil;
  3578. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3579. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3580. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3581. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3582. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3583. else titleSection = NSLocalizedString(titleSection,nil);
  3584. // Formato titolo
  3585. NSString *currentDevice = [CCUtility currentDevice];
  3586. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3587. visualEffectView = [[UIVisualEffectView alloc] init];
  3588. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3589. } else {
  3590. UIVisualEffect *blurEffect;
  3591. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3592. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3593. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3594. }
  3595. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3596. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3597. else shift = - 20;
  3598. } else shift = - 10;
  3599. // Title
  3600. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3601. titleLabel.backgroundColor = [UIColor clearColor];
  3602. titleLabel.textColor = [UIColor blackColor];
  3603. titleLabel.font = [UIFont systemFontOfSize:12];
  3604. titleLabel.textAlignment = NSTextAlignmentLeft;
  3605. titleLabel.text = titleSection;
  3606. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3607. [visualEffectView addSubview:titleLabel];
  3608. // Elements
  3609. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3610. elementLabel.backgroundColor = [UIColor clearColor];
  3611. elementLabel.textColor = [UIColor blackColor];;
  3612. elementLabel.font = [UIFont systemFontOfSize:12];
  3613. elementLabel.textAlignment = NSTextAlignmentRight;
  3614. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3615. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3616. NSUInteger rowsCount = [metadatas count];
  3617. if (rowsCount == 0) return nil;
  3618. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3619. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3620. [visualEffectView addSubview:elementLabel];
  3621. return visualEffectView;
  3622. }
  3623. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3624. {
  3625. return [_sectionDataSource.sections indexOfObject:title];
  3626. }
  3627. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3628. {
  3629. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3630. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3631. else
  3632. return nil;
  3633. }
  3634. /*
  3635. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3636. {
  3637. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3638. }
  3639. }
  3640. */
  3641. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3642. {
  3643. NSString *typeCell;
  3644. NSString *dataFile;
  3645. NSString *lunghezzaFile;
  3646. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3647. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3648. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3649. }
  3650. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3651. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3652. else typeCell = @"CellMainTransfer";
  3653. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3654. // separator
  3655. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3656. // change color selection
  3657. UIView *selectionColor = [[UIView alloc] init];
  3658. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3659. cell.selectedBackgroundView = selectionColor;
  3660. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3661. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3662. // ----------------------------------------------------------------------------------------------------------
  3663. // DEFAULT
  3664. // ----------------------------------------------------------------------------------------------------------
  3665. cell.file.image = nil;
  3666. cell.status.image = nil;
  3667. cell.favorite.image = nil;
  3668. cell.shared.image = nil;
  3669. cell.local.image = nil;
  3670. cell.labelTitle.enabled = YES;
  3671. cell.labelTitle.text = @"";
  3672. cell.labelInfoFile.enabled = YES;
  3673. cell.labelInfoFile.text = @"";
  3674. cell.progressView.progress = 0.0;
  3675. cell.progressView.hidden = YES;
  3676. cell.cancelTaskButton.hidden = YES;
  3677. cell.reloadTaskButton.hidden = YES;
  3678. cell.stopTaskButton.hidden = YES;
  3679. // Encrypted color
  3680. if (metadata.cryptated) {
  3681. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3682. } else {
  3683. cell.labelTitle.textColor = [UIColor blackColor];
  3684. }
  3685. // ----------------------------------------------------------------------------------------------------------
  3686. // File Name & Folder
  3687. // ----------------------------------------------------------------------------------------------------------
  3688. // nome del file
  3689. cell.labelTitle.text = metadata.fileNamePrint;
  3690. // è una directory
  3691. if (metadata.directory) {
  3692. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3693. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3694. lunghezzaFile = @" ";
  3695. // ----------------------------------------------------------------------------------------------------------
  3696. // Favorite Folder
  3697. // ----------------------------------------------------------------------------------------------------------
  3698. if (metadata.favorite) {
  3699. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3700. }
  3701. } else {
  3702. // File
  3703. dataFile = [CCUtility dateDiff:metadata.date];
  3704. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3705. // Plist ancora da scaricare
  3706. if (metadata.cryptated && [metadata.title length] == 0) {
  3707. dataFile = @" ";
  3708. lunghezzaFile = @" ";
  3709. }
  3710. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3711. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3712. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3713. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3714. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3715. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3716. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3717. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3718. cell.local.image = [UIImage imageNamed:@"local"];
  3719. else
  3720. cell.local.image = nil;
  3721. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3722. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3723. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3724. }
  3725. // Plist ancora da scaricare
  3726. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3727. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3728. cell.accessoryType = UITableViewCellAccessoryNone;
  3729. }
  3730. // ----------------------------------------------------------------------------------------------------------
  3731. // File Image View
  3732. // ----------------------------------------------------------------------------------------------------------
  3733. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3734. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3735. cell.file.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3736. if (cell.file.image == nil) {
  3737. NSString *fileID = metadata.fileID;
  3738. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3739. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3740. [app.icoImagesCache setObject:image forKey:fileID];
  3741. dispatch_async(dispatch_get_main_queue(), ^{
  3742. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3743. if (cell)
  3744. cell.file.image = image;
  3745. });
  3746. });
  3747. }
  3748. } else {
  3749. if (metadata.directory)
  3750. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3751. else
  3752. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3753. if (metadata.thumbnailExists)
  3754. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3755. }
  3756. // ----------------------------------------------------------------------------------------------------------
  3757. // Image Status cyptated & Lock Passcode
  3758. // ----------------------------------------------------------------------------------------------------------
  3759. // File Cyptated
  3760. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3761. cell.status.image = [UIImage imageNamed:@"lock"];
  3762. }
  3763. // Directory con passcode lock attivato
  3764. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3765. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3766. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3767. cell.status.image = [UIImage imageNamed:@"passcode"];
  3768. // ----------------------------------------------------------------------------------------------------------
  3769. // Favorite
  3770. // ----------------------------------------------------------------------------------------------------------
  3771. if (metadata.favorite) {
  3772. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3773. }
  3774. // ----------------------------------------------------------------------------------------------------------
  3775. // Share
  3776. // ----------------------------------------------------------------------------------------------------------
  3777. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3778. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3779. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3780. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3781. // Aggiungiamo il Tap per le shared
  3782. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3783. if (isShare) {
  3784. if (metadata.directory) {
  3785. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3786. cell.shared.userInteractionEnabled = NO;
  3787. } else {
  3788. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3789. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3790. [tap setNumberOfTapsRequired:1];
  3791. cell.shared.userInteractionEnabled = YES;
  3792. [cell.shared addGestureRecognizer:tap];
  3793. }
  3794. }
  3795. if (isMounted) {
  3796. if (metadata.directory) {
  3797. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3798. cell.shared.userInteractionEnabled = NO;
  3799. } else {
  3800. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3801. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3802. [tap setNumberOfTapsRequired:1];
  3803. cell.shared.userInteractionEnabled = YES;
  3804. [cell.shared addGestureRecognizer:tap];
  3805. }
  3806. }
  3807. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3808. if (metadata.directory) {
  3809. if ([shareLink length] > 0)
  3810. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3811. if ([shareUserAndGroup length] > 0)
  3812. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3813. cell.shared.userInteractionEnabled = NO;
  3814. } else {
  3815. if ([shareLink length] > 0)
  3816. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3817. if ([shareUserAndGroup length] > 0)
  3818. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3819. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3820. [tap setNumberOfTapsRequired:1];
  3821. cell.shared.userInteractionEnabled = YES;
  3822. [cell.shared addGestureRecognizer:tap];
  3823. }
  3824. }
  3825. } else {
  3826. cell.shared.userInteractionEnabled = NO;
  3827. }
  3828. // ----------------------------------------------------------------------------------------------------------
  3829. // downloadFile
  3830. // ----------------------------------------------------------------------------------------------------------
  3831. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3832. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3833. else cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3834. // sessionTaskIdentifier : RELOAD + STOP
  3835. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3836. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3837. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3838. cell.cancelTaskButton.hidden = NO;
  3839. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3840. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3841. cell.reloadTaskButton.hidden = NO;
  3842. }
  3843. // sessionTaskIdentifierPlist : RELOAD
  3844. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3845. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3846. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3847. cell.reloadTaskButton.hidden = NO;
  3848. }
  3849. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3850. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3851. if (progress > 0) {
  3852. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3853. else cell.progressView.progressTintColor = [UIColor blackColor];
  3854. cell.progressView.progress = progress;
  3855. cell.progressView.hidden = NO;
  3856. }
  3857. // ----------------------------------------------------------------------------------------------------------
  3858. // downloadFile Error
  3859. // ----------------------------------------------------------------------------------------------------------
  3860. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3861. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3862. if ([metadata.sessionError length] == 0)
  3863. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3864. else
  3865. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3866. }
  3867. }
  3868. // ----------------------------------------------------------------------------------------------------------
  3869. // uploadFile
  3870. // ----------------------------------------------------------------------------------------------------------
  3871. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3872. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3873. else cell.status.image = [UIImage imageNamed:@"statusupload"];
  3874. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3875. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3876. cell.cancelTaskButton.hidden = NO;
  3877. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3878. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3879. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3880. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusstopcrypto"];
  3881. else cell.status.image = [UIImage imageNamed:@"statusstop"];
  3882. cell.reloadTaskButton.hidden = NO;
  3883. cell.stopTaskButton.hidden = YES;
  3884. } else {
  3885. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3886. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3887. cell.stopTaskButton.hidden = NO;
  3888. cell.reloadTaskButton.hidden = YES;
  3889. }
  3890. // se non c'è una preview in bianconero metti l'immagine di default
  3891. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3892. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3893. cell.labelTitle.enabled = NO;
  3894. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3895. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3896. if (progress > 0) {
  3897. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3898. else cell.progressView.progressTintColor = [UIColor blackColor];
  3899. cell.progressView.progress = progress;
  3900. cell.progressView.hidden = NO;
  3901. }
  3902. // ----------------------------------------------------------------------------------------------------------
  3903. // uploadFileError
  3904. // ----------------------------------------------------------------------------------------------------------
  3905. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3906. cell.labelTitle.enabled = NO;
  3907. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3908. if ([metadata.sessionError length] == 0)
  3909. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3910. else
  3911. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3912. }
  3913. }
  3914. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3915. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3916. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3917. return cell;
  3918. }
  3919. - (void)setTableViewFooter
  3920. {
  3921. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3922. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3923. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3924. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3925. UIFont *appFont = [UIFont systemFontOfSize:12];
  3926. footerLabel.font = appFont;
  3927. footerLabel.textColor = [UIColor grayColor];
  3928. footerLabel.backgroundColor = [UIColor clearColor];
  3929. footerLabel.textAlignment = NSTextAlignmentCenter;
  3930. NSString *folders;
  3931. NSString *files;
  3932. NSString *footerText;
  3933. if (_sectionDataSource.directories > 1) {
  3934. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3935. } else if (_sectionDataSource.directories == 1){
  3936. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3937. } else {
  3938. folders = @"";
  3939. }
  3940. if (_sectionDataSource.files > 1) {
  3941. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3942. } else if (_sectionDataSource.files == 1){
  3943. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3944. } else {
  3945. files = @"";
  3946. }
  3947. if ([folders isEqualToString:@""]) {
  3948. footerText = files;
  3949. } else if ([files isEqualToString:@""]) {
  3950. footerText = folders;
  3951. } else {
  3952. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3953. }
  3954. footerLabel.text = footerText;
  3955. [footerView addSubview:footerLabel];
  3956. [self.tableView setTableFooterView:footerView];
  3957. }
  3958. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3959. {
  3960. NSString *textMessage;
  3961. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3962. // settiamo il record file.
  3963. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3964. // se non può essere selezionata deseleziona
  3965. if ([cell isEditing] == NO)
  3966. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3967. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3968. if (self.tableView.editing) {
  3969. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3970. [self setTitle];
  3971. return;
  3972. }
  3973. // test crash
  3974. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3975. if (indexPath.row >= [metadatas count]) return;
  3976. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3977. // se è in corso una sessione
  3978. if ([_metadata.session length] > 0) return;
  3979. if (_metadata.errorPasscode) {
  3980. // se UUID è nil lo sta ancora caricando quindi esci
  3981. if (!_metadata.uuid) return;
  3982. // esiste un hint ??
  3983. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3984. // qui !! la richiesta della nuova passcode
  3985. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3986. // stesso UUID ... la password è stata modificata !!!!!!
  3987. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3988. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3989. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3990. [alertView show];
  3991. } else {
  3992. // UUID diverso.
  3993. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3994. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3995. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3996. [alertView show];
  3997. }
  3998. // chiediamo la passcode e ricarichiamo tutto.
  3999. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4000. viewController.delegate = self;
  4001. viewController.fromType = CCBKPasscodeFromPasscode;
  4002. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4003. viewController.passcodeInputView.maximumLength = 64;
  4004. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4005. viewController.inputViewTitlePassword = NO;
  4006. viewController.title = [NCBrandOptions sharedInstance].brand;
  4007. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4008. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4009. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4010. [self presentViewController:navigationController animated:YES completion:nil];
  4011. }
  4012. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  4013. if (_metadata.cryptated && [_metadata.title length] == 0) {
  4014. NSString* selector;
  4015. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  4016. else selector = selectorLoadPlist;
  4017. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4018. return;
  4019. }
  4020. // se il plist è caricato ed è un modello aprilo
  4021. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  4022. // file
  4023. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  4024. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  4025. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  4026. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  4027. } else {
  4028. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4029. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  4030. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  4031. }
  4032. }
  4033. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  4034. }
  4035. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  4036. {
  4037. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  4038. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  4039. [self setTitle];
  4040. }
  4041. #pragma --------------------------------------------------------------------------------------------
  4042. #pragma mark ===== Navigation ====
  4043. #pragma --------------------------------------------------------------------------------------------
  4044. - (BOOL)shouldPerformSegue
  4045. {
  4046. // if background return
  4047. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4048. if (self.view.window == NO)
  4049. return NO;
  4050. // Collapsed ma siamo già in detail esci
  4051. if (self.splitViewController.isCollapsed)
  4052. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4053. // Video in esecuzione esci
  4054. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4055. return YES;
  4056. }
  4057. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4058. {
  4059. id viewController = segue.destinationViewController;
  4060. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4061. tableMetadata *metadata;
  4062. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4063. UINavigationController *nav = viewController;
  4064. _detailViewController = (CCDetail *)nav.topViewController;
  4065. } else {
  4066. _detailViewController = segue.destinationViewController;
  4067. }
  4068. if ([sender isKindOfClass:[tableMetadata class]]) {
  4069. metadata = sender;
  4070. [allRecordsDataSourceImagesVideos addObject:sender];
  4071. } else {
  4072. metadata = _metadata;
  4073. for (NSString *fileID in _sectionDataSource.allEtag) {
  4074. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4075. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4076. [allRecordsDataSourceImagesVideos addObject:metadata];
  4077. }
  4078. }
  4079. _detailViewController.metadataDetail = metadata;
  4080. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4081. _detailViewController.dateFilterQuery = nil;
  4082. [_detailViewController setTitle:metadata.fileNamePrint];
  4083. }
  4084. // can i go to next viewcontroller
  4085. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4086. {
  4087. NSString *nomeDir;
  4088. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4089. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4090. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4091. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  4092. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4093. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4094. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4095. viewController.delegate = self;
  4096. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4097. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4098. viewController.inputViewTitlePassword = YES;
  4099. if ([CCUtility getSimplyBlockCode]) {
  4100. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4101. viewController.passcodeInputView.maximumLength = 6;
  4102. } else {
  4103. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4104. viewController.passcodeInputView.maximumLength = 64;
  4105. }
  4106. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4107. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4108. viewController.touchIDManager = touchIDManager;
  4109. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4110. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4111. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4112. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4113. [self presentViewController:navController animated:YES completion:nil];
  4114. return;
  4115. }
  4116. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4117. else nomeDir = _metadata.fileName;
  4118. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4119. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4120. if (viewController.isViewLoaded == false || viewController == nil) {
  4121. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4122. viewController.isFolderEncrypted = _metadata.cryptated;
  4123. viewController.serverUrl = serverUrlPush;
  4124. viewController.titleMain = _metadata.fileNamePrint;
  4125. viewController.textBackButton = _titleMain;
  4126. // save self
  4127. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4128. }
  4129. // OFF SearchBar
  4130. [viewController cancelSearchBar];
  4131. [self.navigationController pushViewController:viewController animated:YES];
  4132. }
  4133. }
  4134. @end