CCMain.m 253 KB

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