CCMain.m 254 KB

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