CCMain.m 253 KB

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